<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ asynchronous programming - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ asynchronous programming - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 22:38:20 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/asynchronous-programming/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous Programming in JavaScript – Callbacks, Promises, & Async/Await Examples ]]>
                </title>
                <description>
                    <![CDATA[ All programming languages have runtime engines that execute their code. In JavaScript, the runtime engine is single-threaded, which means that it runs code line by line or sequentially. The JavaScript runtime engine makes it a synchronous programming... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-programming-in-javascript-examples/</link>
                <guid isPermaLink="false">66d46042b3016bf139028d63</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Musab Habeeb ]]>
                </dc:creator>
                <pubDate>Fri, 02 Feb 2024 16:04:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Await-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>All programming languages have runtime engines that execute their code. In JavaScript, the runtime engine is single-threaded, which means that it runs code line by line or sequentially.</p>
<p>The JavaScript runtime engine makes it a synchronous programming language where programs run sequentially. Programming languages that are not synchronous are called asynchronous programming languages, which are programming languages where programs run concurrently.</p>
<p>Although JavaScript is synchronous, you can perform asynchronous programming with it. In this article, you will learn about asynchronous programming in JavaScript and how to use it.</p>
<h2 id="heading-what-is-asynchronous-programming">What is Asynchronous Programming?</h2>
<p>Asynchronous programming is a technique that allows your program to run its tasks concurrently. You can compare asynchronous programming to a chef with multiple cookers, pots, and kitchen utensils. This chef will be able to cook various dishes at a time.</p>
<p>Asynchronous programming makes your JavaScript programs run faster, and you can perform asynchronous programming with any of these:</p>
<ul>
<li><p>Callbacks</p>
</li>
<li><p>Promises</p>
</li>
<li><p>Async/Await</p>
</li>
</ul>
<p>In the upcoming sections, you will learn about these techniques and how to use them.</p>
<h2 id="heading-callbacks">Callbacks</h2>
<p>A callback is a function used as an argument in another function. Callbacks allow you to create asynchronous programs in JavaScript by passing the result of a function into another function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${name}</span>, how do you do?`</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayGreeting</span>(<span class="hljs-params">callback</span>) </span>{
    <span class="hljs-keyword">let</span> name = prompt(<span class="hljs-string">"Please enter your name"</span>);
    callback(name);
};

displayGreeting(greet);
</code></pre>
<p>In the code above, the <code>greet</code> function is used to log a greeting to the console, and it needs the name of the person to be greeted.</p>
<p>The <code>displayGreeting</code> function gets the person's name and has a callback that passes the name as an argument to the <code>greet</code> function while calling it. Then the <code>displayGreeting</code> function is called with the greet function passed to it as an argument.</p>
<h3 id="heading-callback-hell">Callback hell</h3>
<p>Although callbacks make it easy to control and make your program asynchronous, you'll eventually run into a problem called callback hell while using them.</p>
<p>This problem arises when you perform multiple asynchronous tasks with callbacks, which might result in nesting callbacks in callbacks.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">callback</span>) </span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi Musab"</span>);
        callback();
    }, <span class="hljs-number">1000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">introduce</span>(<span class="hljs-params">callback</span>) </span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I am your academic advisor"</span>);
        callback();
    }, <span class="hljs-number">1000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">question</span>(<span class="hljs-params">callback</span>) </span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Are you currently facing any challenge in your academics"</span>);;
        callback();
    }, <span class="hljs-number">1000</span>);
}

<span class="hljs-comment">// callback hell</span>
greet(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    introduce(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        question(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Done"</span>);
        });
    });
});
</code></pre>
<p>In the code above, the <code>greet</code>, <code>introduce</code>, and <code>question</code> functions are nested to create a callback hell, which makes error handling difficult. You should change your asynchronous programming technique from callbacks to <code>Promise</code> to avoid the callback hell.</p>
<h2 id="heading-promise">Promise</h2>
<p>Most programs consist of a producing code that performs a time-consuming task and a consuming code that needs the result of the producing code.</p>
<p>A <code>Promise</code> links the producing and the consuming code together. In the example below, the <code>displayGreeting</code> function is the producing code while the <code>greet</code> function is the consuming code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name;

<span class="hljs-comment">// producing code</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayGreeting</span>(<span class="hljs-params">callback</span>) </span>{
    name = prompt(<span class="hljs-string">"Please enter your name"</span>);
}

<span class="hljs-comment">// consuming code</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${name}</span>, how do you do?`</span>);
}
</code></pre>
<p>In the example below, the <code>new Promise</code> syntax creates a new <code>Promise</code>, which takes a function that executes the producing code. The function either resolves or rejects its task and assigns the <code>Promise</code> to a variable named <code>promise</code>.</p>
<p>If the producing code resolves, its result will be passed to the consuming code through the <code>.then</code> handler.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayGreeting</span>(<span class="hljs-params"></span>) </span>{
    name = prompt(<span class="hljs-string">"Please enter your name"</span>);
}

<span class="hljs-keyword">let</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
    <span class="hljs-comment">// the producing code</span>
    displayGreeting();
    resolve(name)
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">result</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${result}</span>, how do you do?`</span>);
}

promise.then(
    <span class="hljs-comment">// the consuming code</span>
    <span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> greet(result),
    <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> alert(error)
);
</code></pre>
<p>You can convert the previous callback hell's example to a promise by returning a promise from each function and chaining the function calls together with the <code>.then</code> handler.</p>
<p>You can also use the <code>.catch</code> handler to catch any error thrown during the function execution.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi Musab"</span>);
            resolve();
        }, <span class="hljs-number">1000</span>);
    });  
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">introduce</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I am your academic advisor"</span>);
            resolve();
        }, <span class="hljs-number">1000</span>);
    });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">question</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Are you currently facing any challenge in your academics"</span>);;
            resolve();
        }, <span class="hljs-number">1000</span>);
    });
}

greet()
    .then(<span class="hljs-function">() =&gt;</span> introduce())
    .then(<span class="hljs-function">() =&gt;</span> question())
    .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Done"</span>))
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"An error occured: "</span>, error));
</code></pre>
<h3 id="heading-what-are-the-states-of-a-promise-in-javascript">What are the States of a Promise in JavaScript?</h3>
<p>A promise can be in any of these three states:</p>
<ul>
<li><p>Pending: This is the initial state of the promise and its state while it's still running.</p>
</li>
<li><p>Fulfilled: This is the state of the promise when it resolves successfully.</p>
</li>
<li><p>Rejected: This is the state of the promise when errors make it not to be resolved.</p>
</li>
</ul>
<h2 id="heading-asyncawait">Async/Await</h2>
<p><code>async</code>/<code>await</code> is syntactic sugar for creating a <code>Promise</code> — it makes creating promises easier.</p>
<p>To make a function asynchronous using <code>async</code>/<code>await</code>, you have to write the <code>async</code> keyword before the function declaration. Then, you can write the <code>await</code> keyword before the producing code's execution call.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayGreeting</span>(<span class="hljs-params"></span>) </span>{
    name = prompt(<span class="hljs-string">"Please enter your name"</span>);
    <span class="hljs-keyword">return</span> name;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">result</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${result}</span>, how do you do?`</span>);
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// the producing code</span>
    <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">await</span> displayGreeting();
    <span class="hljs-comment">// the consuming code</span>
    greet(result);
};

greeting();
</code></pre>
<p>In the example above, the producing code is the <code>displayGreeting</code> function, and the consuming code is the <code>greet</code> function. The <code>greeting</code> function is the <code>Promise</code> that connects the producing and the consuming code. It waits for the result returned from the <code>displayGreeting</code> function and passes that result to the greet function.</p>
<h3 id="heading-error-handling-in-asyncawait">Error Handling in Async/Await</h3>
<p>You can easily handle errors that arise when you perform asynchronous operations with <code>async</code>/<code>await</code> using the <code>try...catch</code> statement. The asynchronous operation executes in the <code>try</code> block, and you can handle errors in the <code>catch</code> block.</p>
<p>That is:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">await</span> displayGreeting();
        greet(result);
    } <span class="hljs-keyword">catch</span>(err) {
        <span class="hljs-built_in">console</span>.error(err)
    }
};
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Asynchronous programming in JavaScript is used to make tasks in a program run concurrently and uses techniques such as callbacks, <code>Promise</code>, or <code>async</code>/<code>await</code>.</p>
<p>This article explains how to use these asynchronous programming techniques and how to handle errors with them.</p>
<p>You can check the <a target="_blank" href="https://javascript.info/async">promises and async/await section on the JavaScript.info website</a> to learn more about asynchronous programming in JavaScript.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous JavaScript – How to Use Promises in Your JS Code ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is a versatile programming language that powers the dynamic behavior of websites.  As web applications become more sophisticated, the need to handle asynchronous operations efficiently becomes crucial. Asynchronous JavaScript allows you to... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-promises-in-javascript/</link>
                <guid isPermaLink="false">66c4c3e5e486f65d4125b7ff</guid>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Mon, 11 Dec 2023 21:52:05 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/Orange-and-white-modern-creative-marketing-plan-Presentation-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is a versatile programming language that powers the dynamic behavior of websites. </p>
<p>As web applications become more sophisticated, the need to handle asynchronous operations efficiently becomes crucial. Asynchronous JavaScript allows you to execute code without blocking the main thread, ensuring a smoother user experience. </p>
<p>Promises are a powerful tool in JavaScript for managing asynchronous operations, providing a cleaner and more organized approach to handling asynchronous code.</p>
<p>Here's what we'll cover:</p>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-asynchronous-javascript">What is asynchronous JavaScript?</a></li>
<li><a class="post-section-overview" href="#heading-the-need-for-promises">The need for promises</a></li>
<li><a class="post-section-overview" href="#heading-what-is-callback-hell">What is callback hell?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-promise">How to create a promise</a></li>
<li><a class="post-section-overview" href="#heading-how-to-consume-promises-with-then-and-catch">How to consume promises with <code>.then()</code> and <code>.catch()</code></a></li>
<li><a class="post-section-overview" href="#heading-how-to-chain-promises-with-then">How to chain promises with <code>.then()</code></a></li>
<li><a class="post-section-overview" href="#heading-more-complex-examples-of-promise-chaining">More complex examples of promise chaining</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-errors-with-catch">How to handle errors with <code>.catch()</code></a></li>
<li><a class="post-section-overview" href="#heading-error-handling-in-more-detail">Error handling in more detail</a></li>
<li><a class="post-section-overview" href="#heading-asyncawait-in-javascript">Async/await in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-alternative-asynchronous-programming-methods">Alternative asynchronous programming methods</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-asynchronous-javascript">What is Asynchronous JavaScript?</h2>
<p>JavaScript is single-threaded, meaning it can only execute one operation at a time. However, in web development, there are tasks that take time to complete, such as fetching data from an API, reading a file, or waiting for a user input. If these tasks were executed synchronously, they would block the main thread, making the user interface unresponsive.</p>
<p>Asynchronous JavaScript allows you to execute code without waiting for the completion of time-consuming tasks. Instead of blocking the main thread, these tasks are delegated to the browser's background processes, and once completed, a callback function is triggered to handle the result.</p>
<h2 id="heading-the-need-for-promises">The Need for Promises</h2>
<p>Before Promises, developers used callbacks to handle asynchronous operations. Callbacks are functions passed as arguments to other functions, and they are executed once the asynchronous operation is completed. </p>
<p>While callbacks serve their purpose, they often lead to a phenomenon known as "callback hell" – a situation where multiple nested callbacks make the code hard to read and maintain.</p>
<p>Callback hell arises when asynchronous operations depend on the results of other asynchronous operations, creating deeply nested callback functions. This can make the code difficult to follow, debug, and maintain. </p>
<p>Promises were introduced to address this issue and provide a more elegant solution to asynchronous code.</p>
<h2 id="heading-what-is-callback-hell">What is Callback Hell?</h2>
<p>Callback hell, also known as the "pyramid of doom," occurs when you have multiple nested callbacks within your code. Each level of nesting represents a subsequent asynchronous operation that depends on the result of the previous one. Here's a simplified example:</p>
<pre><code class="lang-javascript">getData(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) </span>{
  processData(data, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">processedData</span>) </span>{
    updateUI(processedData, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-comment">// More nested callbacks...</span>
    });
  });
});
</code></pre>
<p>As you can see, as the number of asynchronous operations increases, the code indentation deepens, leading to a less readable and maintainable codebase. </p>
<p>Promises provide a way to mitigate callback hell by offering a cleaner and more structured approach to handling asynchronous code.</p>
<h2 id="heading-how-to-create-a-promise">How to Create a Promise</h2>
<p>Let's dive into the basics of creating a promise. The <code>Promise</code> constructor takes a function as its argument, which has two parameters: <code>resolve</code> and <code>reject</code>. These parameters are functions that you call to indicate the completion or failure of the asynchronous operation.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating a Promise that resolves to success</span>
<span class="hljs-keyword">const</span> successPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-comment">// Simulating a successful asynchronous operation</span>
  <span class="hljs-keyword">const</span> success = <span class="hljs-literal">true</span>;

  <span class="hljs-keyword">if</span> (success) {
    resolve(<span class="hljs-string">"Operation completed successfully"</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">"Operation failed"</span>);
  }
});

<span class="hljs-comment">// Creating a Promise that resolves to an error</span>
<span class="hljs-keyword">const</span> errorPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-comment">// Simulating a failed asynchronous operation</span>
  <span class="hljs-keyword">const</span> success = <span class="hljs-literal">false</span>;

  <span class="hljs-keyword">if</span> (success) {
    resolve(<span class="hljs-string">"Operation completed successfully"</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">"Operation failed"</span>);
  }
});
</code></pre>
<p>In the <code>successPromise</code>, the asynchronous operation is simulated to be successful, and <code>resolve</code> is called with the success message. In the <code>errorPromise</code>, the operation is simulated to fail, and <code>reject</code> is called with the error message.</p>
<h2 id="heading-how-to-consume-promises-with-then-and-catch">How to Consume Promises with <code>.then()</code> and <code>.catch()</code></h2>
<p>Once a promise is created, you can consume its result using the <code>.then()</code> and <code>.catch()</code> methods. The <code>.then()</code> method is used when the promise is fulfilled, and the <code>.catch()</code> method is used when the promise is rejected.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Consuming the successPromise</span>
successPromise
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: Operation completed successfully</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(error); <span class="hljs-comment">// This won't be executed</span>
  });

<span class="hljs-comment">// Consuming the errorPromise</span>
errorPromise
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// This won't be executed</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(error); <span class="hljs-comment">// Output: Operation failed</span>
  });
</code></pre>
<p>In the example above, the <code>.then()</code> method logs the success message for <code>successPromise</code> and the error message for <code>errorPromise</code>. The <code>.catch()</code> method handles errors for both Promises.</p>
<h2 id="heading-how-to-chain-promises-with-then">How to Chain Promises with <code>.then()</code></h2>
<p>One of the powerful features of promises is the ability to chain them together using the <code>.then()</code> method. This is especially useful when you have multiple asynchronous operations that depend on each other.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">"First operation completed"</span>);
  }, <span class="hljs-number">1000</span>);
});

<span class="hljs-keyword">const</span> secondPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">"Second operation completed"</span>);
  }, <span class="hljs-number">500</span>);
});

<span class="hljs-keyword">const</span> thirdPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">"Third operation completed"</span>);
  }, <span class="hljs-number">800</span>);
});

firstPromise
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: First operation completed</span>
    <span class="hljs-keyword">return</span> secondPromise;
  })
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: Second operation completed</span>
    <span class="hljs-keyword">return</span> thirdPromise;
  })
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: Third operation completed</span>
  });
</code></pre>
<p>In this example, the second and third promises are chained to the first one using the <code>return</code> statement inside the <code>.then()</code> callbacks. This ensures that each promise waits for the completion of the previous one before executing.</p>
<h2 id="heading-more-complex-examples-of-promise-chaining">More Complex Examples of Promise Chaining</h2>
<p>Let's explore more complex examples of promise chaining to demonstrate how it can be applied in real-world scenarios.</p>
<h3 id="heading-example-1-fetching-user-data-and-posts">Example 1: Fetching User Data and Posts</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchUserData</span>(<span class="hljs-params">userId</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">// Simulating fetching user data from an API</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">const</span> userData = { <span class="hljs-attr">id</span>: userId, <span class="hljs-attr">username</span>: <span class="hljs-string">'john_doe'</span> };
      resolve(userData);
    }, <span class="hljs-number">1000</span>);
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchUserPosts</span>(<span class="hljs-params">userId</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">// Simulating fetching user posts from an API</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">const</span> posts = [
        { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Post 1'</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">'Post 2'</span> },
      ];
      resolve(posts);
    }, <span class="hljs-number">800</span>);
  });
}

<span class="hljs-comment">// Chaining promises to fetch user data and posts sequentially</span>
fetchUserData(<span class="hljs-number">123</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">userData</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(userData); <span class="hljs-comment">// Output: { id: 123, username: 'john_doe' }</span>
    <span class="hljs-keyword">return</span> fetchUserPosts(userData.id);
  })
  .then(<span class="hljs-function">(<span class="hljs-params">userPosts</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(userPosts); <span class="hljs-comment">// Output: [{ id: 1, title: 'Post 1' }, { id: 2, title: 'Post 2' }]</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
  });
</code></pre>
<p>In this example, two asynchronous operations (<code>fetchUserData</code> and <code>fetchUserPosts</code>) are chained to fetch user data and posts sequentially.</p>
<h3 id="heading-example-2-processing-data-with-multiple-steps">Example 2: Processing Data with Multiple Steps</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processData</span>(<span class="hljs-params">data</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">// Simulating data processing</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">const</span> processedData = data.map(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> item * <span class="hljs-number">2</span>);
      resolve(processedData);
    }, <span class="hljs-number">500</span>);
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayData</span>(<span class="hljs-params">data</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">// Simulating displaying data</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(data); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>
      resolve(<span class="hljs-string">'Data displayed successfully'</span>);
    }, <span class="hljs-number">300</span>);
  });
}

<span class="hljs-comment">// Chaining promises to process and display data sequentially</span>
<span class="hljs-keyword">const</span> originalData = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
processData(originalData)
  .then(<span class="hljs-function">(<span class="hljs-params">processedData</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(processedData); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>
    <span class="hljs-keyword">return</span> displayData(processedData);
  })
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: Data displayed successfully</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
  });
</code></pre>
<p>In this example, two asynchronous operations (<code>processData</code> and <code>displayData</code>) are chained to process and display data sequentially.</p>
<h2 id="heading-how-to-handle-errors-with-catch">How to Handle Errors with <code>.catch()</code></h2>
<p>When working with asynchronous operations, handling errors is crucial. Promises make error handling more manageable by providing the <code>.catch()</code> method, which is used to catch any errors that occur during the Promise chain.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> errorPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> success = <span class="hljs-literal">false</span>;

    <span class="hljs-keyword">if</span> (success) {
      resolve(<span class="hljs-string">"Operation completed successfully"</span>);
    } <span class="hljs-keyword">else</span> {
      reject(<span class="hljs-string">"Operation failed"</span>);
    }
  }, <span class="hljs-number">1000</span>);
});

errorPromise
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// This won't be executed</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(error); <span class="hljs-comment">// Output: Operation failed</span>
  });
</code></pre>
<p>In this example, since the <code>success</code> variable is set to <code>false</code>, the promise is rejected, and the <code>.catch()</code> method is invoked with the reason for failure.</p>
<h2 id="heading-error-handling-in-more-detail">Error Handling in More Detail</h2>
<p>While the previous examples touched on error handling, let's delve deeper into the techniques for handling errors with promises.</p>
<h3 id="heading-using-try-catch-blocks">Using Try-Catch Blocks</h3>
<p>You can use try-catch blocks to handle errors within the asynchronous operations themselves.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-keyword">async</span> (resolve, reject) =&gt; {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
      <span class="hljs-keyword">if</span> (!response.ok) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`HTTP error! Status: <span class="hljs-subst">${response.status}</span>`</span>);
      }
      <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
      resolve(data);
    } <span class="hljs-keyword">catch</span> (error) {
      reject(<span class="hljs-string">`Error fetching data: <span class="hljs-subst">${error.message}</span>`</span>);
    }
  });
}

fetchData()
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(error);
  });
</code></pre>
<p>In this example, the <code>try</code> block attempts to fetch data, checks if the response is okay, and then proceeds to parse it as JSON. If any error occurs within the <code>try</code> block, the <code>catch</code> block is executed, and the error is passed to the reject function.</p>
<h3 id="heading-using-the-catch-method">Using the <code>.catch()</code> Method</h3>
<p>You can also use the <code>.catch()</code> method at the end of the promise chain to handle errors that may occur at any stage.</p>
<pre><code class="lang-javascript">fetchData()
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(error);
  });
</code></pre>
<p>This approach is particularly useful when you want to handle errors globally for a sequence of asynchronous operations.</p>
<h3 id="heading-handling-errors-in-promise-chaining">Handling Errors in Promise Chaining</h3>
<p>When chaining Promises, it's important to handle errors at each step of the chain. Here's an example demonstrating error handling in a Promise chain:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepOne</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">// Simulating an asynchronous operation</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">const</span> success = <span class="hljs-literal">true</span>;
      <span class="hljs-keyword">if</span> (success) {
        resolve(<span class="hljs-string">'Step One completed'</span>);
      } <span class="hljs-keyword">else</span> {
        reject(<span class="hljs-string">'Step One failed'</span>);
      }
    }, <span class="hljs-number">500</span>);
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepTwo</span>(<span class="hljs-params">data</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">// Simulating an asynchronous operation</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">const</span> success = <span class="hljs-literal">false</span>;
      <span class="hljs-keyword">if</span> (success) {
        resolve(<span class="hljs-string">`Step Two completed with data: <span class="hljs-subst">${data}</span>`</span>);
      } <span class="hljs-keyword">else</span> {
        reject(<span class="hljs-string">'Step Two failed'</span>);
      }
    }, <span class="hljs-number">300</span>);
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepThree</span>(<span class="hljs-params">result</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    <span class="hljs-comment">// Simulating an asynchronous operation</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      resolve(<span class="hljs-string">`Step Three completed with result: <span class="hljs-subst">${result}</span>`</span>);
    }, <span class="hljs-number">200</span>);
  });
}

stepOne()
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> stepTwo(data))
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> stepThree(result))
  .then(<span class="hljs-function">(<span class="hljs-params">finalResult</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(finalResult); <span class="hljs-comment">// This won't be executed in case of any rejection in the chain</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error in Promise chain:'</span>, error);
  });
</code></pre>
<p>In this example, if any step in the chain encounters an error (either in the asynchronous operation or due to conditional logic), the <code>catch</code> block at the end of the chain will handle the error.</p>
<h2 id="heading-asyncawait-in-javascript">Async/Await in JavaScript</h2>
<p>Async/await is a syntactic sugar introduced in ECMAScript 2017 (ES8) that simplifies the handling of asynchronous code. It provides a more readable and synchronous-like structure, making it easier for developers to work with asynchronous operations.</p>
<h3 id="heading-how-it-works">How it Works:</h3>
<ul>
<li>The <code>async</code> keyword is used to define an asynchronous function. This function always returns a Promise.</li>
<li>The <code>await</code> keyword is used within the async function to pause its execution until the Promise is resolved. It allows you to work with Promises in a more synchronous manner.</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Asynchronous function using async/await</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-comment">// Simulating an asynchronous operation, like fetching data from an API</span>
    <span class="hljs-keyword">let</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);

    <span class="hljs-comment">// Once the Promise is resolved, the code below will execute</span>
    <span class="hljs-keyword">let</span> data = <span class="hljs-keyword">await</span> response.json();

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data:'</span>, data);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
  }
}

<span class="hljs-comment">// Calling the async function</span>
fetchData();
</code></pre>
<p>So what's this code doing?</p>
<ol>
<li>The <code>fetchData</code> function is declared as <code>async</code>, indicating that it contains asynchronous operations.</li>
<li>Inside the function, <code>await fetch(...)</code> is used to make an asynchronous request to a URL, and the function pauses until the request is complete.</li>
<li>After the response is received, <code>await response.json()</code> is used to extract the JSON data from the response.</li>
<li>The <code>try</code> block handles successful execution, and the data is logged to the console.</li>
<li>If any error occurs during the asynchronous operations, the <code>catch</code> block handles the error.</li>
</ol>
<p>Now, let's discuss the pros and cons of async/await.</p>
<h3 id="heading-pros-of-asyncawait">Pros of async/await</h3>
<h4 id="heading-1-readability-and-simplicity">1. <strong>Readability and Simplicity:</strong></h4>
<p>Async/await syntax makes asynchronous code look similar to synchronous code, improving readability and making it easier for developers to understand.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Using Promises</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
}

<span class="hljs-comment">// Using Async/Await</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(data);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  }
}
</code></pre>
<h4 id="heading-2-error-handling">2. <strong>Error Handling:</strong></h4>
<p>Async/await simplifies error handling by allowing the use of traditional try-catch blocks, making it more intuitive to manage errors within asynchronous functions.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Using Promises</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (!response.ok) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`HTTP error! Status: <span class="hljs-subst">${response.status}</span>`</span>);
      }
      <span class="hljs-keyword">return</span> response.json();
    })
    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
}

<span class="hljs-comment">// Using Async/Await</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
    <span class="hljs-keyword">if</span> (!response.ok) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`HTTP error! Status: <span class="hljs-subst">${response.status}</span>`</span>);
    }
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(data);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  }
}
</code></pre>
<h4 id="heading-3-sequential-execution">3. <strong>Sequential Execution:</strong></h4>
<p>Async/await allows developers to write asynchronous code in a more sequential manner, which can be easier to reason about and debug.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Using Promises</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchDataSequentially</span>(<span class="hljs-params"></span>) </span>{
  fetchUserData()
    .then(<span class="hljs-function">(<span class="hljs-params">userData</span>) =&gt;</span> fetchUserPosts(userData.id))
    .then(<span class="hljs-function">(<span class="hljs-params">userPosts</span>) =&gt;</span> processPosts(userPosts))
    .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> displayResult(result))
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
}

<span class="hljs-comment">// Using Async/Await</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchDataSequentially</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> fetchUserData();
    <span class="hljs-keyword">const</span> userPosts = <span class="hljs-keyword">await</span> fetchUserPosts(userData.id);
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> processPosts(userPosts);
    displayResult(result);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  }
}
</code></pre>
<h3 id="heading-cons-of-asyncawait">Cons of async/await</h3>
<h4 id="heading-1-no-built-in-timeout">1. <strong>No Built-In Timeout:</strong></h4>
<p>Async/await doesn't have built-in support for setting a timeout on asynchronous operations. If you need to implement a timeout, you might need to use a combination of <code>Promise.race()</code> and <code>setTimeout</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchDataWithTimeout</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> timeoutPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">_, reject</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Timeout exceeded'</span>)), <span class="hljs-number">5000</span>);
  });

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.race([fetch(<span class="hljs-string">'https://api.example.com/data'</span>), timeoutPromise]);
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(data);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  }
}
</code></pre>
<h4 id="heading-2-sequential-execution-vs-parallelism">2. <strong>Sequential Execution vs. Parallelism:</strong></h4>
<p>While async/await facilitates writing sequential code, it may not be ideal for scenarios where you want parallel execution of independent asynchronous tasks. In such cases, promises and <code>Promise.all()</code> may be more suitable.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Using Promises and Promise.all()</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchAndProcessData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> userDataPromise = fetchUserData();
  <span class="hljs-keyword">const</span>

userPostsPromise = fetchUserPosts();

  <span class="hljs-built_in">Promise</span>.all([userDataPromise, userPostsPromise])
    .then(<span class="hljs-function">(<span class="hljs-params">[userData, userPosts]</span>) =&gt;</span> processAndDisplayData(userData, userPosts))
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
}

<span class="hljs-comment">// Using Async/Await</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchAndProcessData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> fetchUserData();
    <span class="hljs-keyword">const</span> userPosts = <span class="hljs-keyword">await</span> fetchUserPosts();
    processAndDisplayData(userData, userPosts);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  }
}
</code></pre>
<h4 id="heading-3-potential-for-unhandled-promise-rejections">3. <strong>Potential for Unhandled Promise Rejections:</strong></h4>
<p>Async/await may lead to unhandled promise rejections if not used with care. For instance, forgetting to use <code>try-catch</code> blocks or not chaining <code>.catch()</code> at the end of an async function might result in unhandled promise rejections.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
  <span class="hljs-built_in">console</span>.log(data);
}

fetchData(); <span class="hljs-comment">// Unhandled promise rejection if fetch fails</span>
</code></pre>
<p>To mitigate this, make sure you implement proper error handling in all async functions.</p>
<h3 id="heading-using-the-catch-method-1">Using the <code>.catch()</code> Method</h3>
<p>You can also use the <code>.catch()</code> method at the end of the promise chain to handle errors that may occur at any stage.</p>
<pre><code class="lang-javascript">fetchData()
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(error);
  });
</code></pre>
<p>This approach is particularly useful when you want to handle errors globally for a sequence of asynchronous operations.</p>
<h2 id="heading-alternative-asynchronous-programming-methods">Alternative Asynchronous Programming Methods</h2>
<p>While Promises are a popular and powerful tool for asynchronous programming, it's worth mentioning other methods that developers might encounter or choose to use.</p>
<h3 id="heading-asyncawait-syntax">Async/Await Syntax</h3>
<p>As we talked about in the previous section, async/await provides a syntactic sugar on top of promises, making asynchronous code appear more synchronous and readable.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(data);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching data:'</span>, error);
  }
}

fetchData();
</code></pre>
<p>In this example, the <code>async</code> keyword is used to define an asynchronous function, and the <code>await</code> keyword is used to wait for the resolution of the <code>fetch</code> operation and the subsequent <code>json</code> conversion.</p>
<h3 id="heading-web-workers">Web Workers</h3>
<p>Web Workers are a different approach to handling concurrency in JavaScript. They allow you to run scripts in the background, separate from the main thread, to perform tasks without affecting the user interface's responsiveness.</p>
<p>While Web Workers don't directly replace promises, they provide an alternative way to achieve parallelism and handle computationally intensive tasks asynchronously.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Inside a web worker script (worker.js)</span>
self.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> data = event.data;
  <span class="hljs-keyword">const</span> result = processData(data);
  self.postMessage(result);
});

<span class="hljs-comment">// In the main script</span>
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'worker.js'</span>);

worker.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> result = event.data;
  <span class="hljs-built_in">console</span>.log(result);
});

<span class="hljs-keyword">const</span> dataToSend = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
worker.postMessage(dataToSend);
</code></pre>
<p>In this example, a Web Worker script (<code>worker.js</code>) processes data and sends the result back to the main script. Web Workers are a powerful tool for parallelizing tasks and offloading work from the main thread.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Promises offer a clean and organized way to handle asynchronous code in JavaScript, addressing issues such as callback hell and providing a more readable syntax for asynchronous operations. </p>
<p>By understanding the basics of promises, chaining them together, handling errors, and exploring advanced concepts, you can enhance your ability to write efficient and maintainable asynchronous JavaScript code.</p>
<p>While promises are widely adopted, it's essential to be aware of alternative approaches like async/await and Web Workers, as they may better suit specific use cases or preferences. </p>
<p>As you continue to explore and apply different asynchronous programming methods, you'll be better equipped to build responsive, user-friendly web applications. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Asynchronous JavaScript Works ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, you'll learn all about Asynchronous JavaScript. But before we dive into that, we need to make sure you understand what Synchronous code is and how it works. What is Synchronous Code? When we write a program in JavaScript, it execute... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-javascript/</link>
                <guid isPermaLink="false">66d45f6347a8245f78752a74</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Fri, 17 Feb 2023 18:37:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-zhang-kaiyv-1168940.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, you'll learn all about Asynchronous JavaScript.</p>
<p>But before we dive into that, we need to make sure you understand what Synchronous code is and how it works.</p>
<h2 id="heading-what-is-synchronous-code">What is Synchronous Code?</h2>
<p>When we write a program in JavaScript, it executes line by line. When a line is completely executed, then and then only does the code move forward to execute the next line.</p>
<p>Let's look at an example of this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> greet_one = <span class="hljs-string">"Hello"</span>
<span class="hljs-keyword">let</span> greet_two = <span class="hljs-string">"World!!!"</span>
<span class="hljs-built_in">console</span>.log(greet_one)
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>;i&lt;<span class="hljs-number">1000000000</span>;i++){
}
<span class="hljs-built_in">console</span>.log(greet_two);
</code></pre>
<p>Now if you run the above example on your machine you will notice that <code>greet_one</code> logs first. Then the program waits for a couple of seconds and then logs <code>greet_two</code>. This is because the code executes line by line. This is called synchronous code.</p>
<p>This creates lot of problems. For example, if a certain piece of code takes 10 seconds to execute, the code after it won't be able to execute until it's finished, causing delays.</p>
<h2 id="heading-what-is-asynchronous-code">What is Asynchronous Code?</h2>
<p>With asynchronous code, multiple tasks can execute at the same time while tasks in the background finish. This is what we call non-blocking code. The execution of other code won't stop while an asynchronous task finishes its work.</p>
<p>Let's see an example of asynchronous code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> greet_one = <span class="hljs-string">"Hello"</span>
<span class="hljs-keyword">let</span> greet_two = <span class="hljs-string">"World!!!"</span>
<span class="hljs-built_in">console</span>.log(greet_one)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Asynchronous"</span>);
}, <span class="hljs-number">10000</span>)
<span class="hljs-built_in">console</span>.log(greet_two);
</code></pre>
<p>In the above example, if you run the code on your machine you will see <code>greet_one</code> and <code>greet_two</code> logged even there is code in between those 2 logs.</p>
<p>Now, setTimeout is asynchronous so it runs in background, allowing code after it to execute while it runs. After 10 seconds, <code>Asynchronous</code> will print because we set a time of 10 seconds in setTimeout to execute it after 10 seconds.</p>
<p>In this tutorial, we will study asynchronous JavaScript in detail so you can learn how to write your own asynchronous code. I just wanted to give you a taste of async JavaScript using in-built functions to whet your appetite.</p>
<h1 id="heading-how-callbacks-work-in-javascript">How Callbacks Work in JavaScript</h1>
<blockquote>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">"A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action."</a> (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">MDN</a>)</p>
</blockquote>
<p>Let's look at a code example to see why using callbacks instead would be helpful:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">compute</span>(<span class="hljs-params">action, x, y</span>)</span>{
    <span class="hljs-keyword">if</span>(action === <span class="hljs-string">"add"</span>){
        <span class="hljs-keyword">return</span> x+y
    }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(action === <span class="hljs-string">"divide"</span>){
        <span class="hljs-keyword">return</span> x/y
    }
}

<span class="hljs-built_in">console</span>.log(compute(<span class="hljs-string">"add"</span>,<span class="hljs-number">10</span>,<span class="hljs-number">5</span>))   
<span class="hljs-built_in">console</span>.log(compute(<span class="hljs-string">"divide"</span>,<span class="hljs-number">10</span>,<span class="hljs-number">5</span>))
</code></pre>
<p>In the above example, we have two operations. But what if we want to add more operations? Then the number of if/else statements would increase. This code would be lengthy, so we use callbacks instead:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">x,y</span>)</span>{
    <span class="hljs-keyword">return</span> x+y
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">divide</span>(<span class="hljs-params">x,y</span>)</span>{
    <span class="hljs-keyword">return</span> x/y
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">compute</span>(<span class="hljs-params">callBack, x, y</span>)</span>{
    <span class="hljs-keyword">return</span> callBack(x,y)
}

<span class="hljs-built_in">console</span>.log(compute(add, <span class="hljs-number">10</span>, <span class="hljs-number">5</span>))    <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(compute(divide, <span class="hljs-number">10</span>, <span class="hljs-number">5</span>))
</code></pre>
<p>Now when we call <code>compute</code> with three arguments, one of them is an operation. When we enter in the compute function, the function returns a function with a given action name. It, in response, calls that function and returns the result.</p>
<h2 id="heading-welcome-to-callback-hell">Welcome to Callback Hell</h2>
<p>Callbacks are great, but you don't want to use them excessively. If you do, you'll get something called "callback hell". This happens when you nest callbacks within callbacks many levels deep.</p>
<p>The shape of callback hell is like a pyramid and is also called the “pyramid of doom”. It makes the code very difficult to maintain and understand. Here's an example of callback hell:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"One Second"</span>);
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Two Seconds"</span>);
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Three Seconds"</span>);
            <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Four Seconds"</span>);
                <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
                    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Five Seconds"</span>);
                }, <span class="hljs-number">1000</span>)
            }, <span class="hljs-number">1000</span>)
        }, <span class="hljs-number">1000</span>)
    }, <span class="hljs-number">1000</span>)
}, <span class="hljs-number">1000</span>)
</code></pre>
<p>When one second has passed, the code logs "one seconds". Then there's another call which runs after one more second and logs "two seconds" and it goes on and on.</p>
<p>We can escape this callback hell using something call <code>Promises</code> in asynchronous JavaScript.</p>
<h1 id="heading-how-promises-work-in-javascript">How Promises Work in JavaScript</h1>
<p>A promise is placeholder for the future result of an asynchronous operation. In simple words, we can say it is a container for a future value.</p>
<p>When using promises, we don't need to relay on callbacks which helps us avoid callback hell.</p>
<p>Before showing you how promises work through code, I'll explain promises using the analogy of a lottery ticket.</p>
<p>Promises are like lottery ticket. When we buy a lottery ticket, it says we will get money if our outcome is right. This is like a promise. The lottery draw happens asynchronously, and if the numbers match, we receive the money which was promised.</p>
<p>Now let's look at a code example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>)
<span class="hljs-built_in">console</span>.log(request);
</code></pre>
<p>The above code is using fetch for a request from an API. It returns a promise which will get a response from the server.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/1212.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is how a promise looks. It has a particular promise state and result. When a promise is created it runs asynchronously. When the given task is completed, then we say the promise is settled. After the promise is settled, we can have either a fulfilled or rejected promise state based on the outcome of the promise. We can handle these different states in different ways in our code.</p>
<h3 id="heading-how-to-consume-promises">How to Consume Promises</h3>
<p>We can consume a promise using the then() method on the promise. Producing code is code that can take some time to complete. Consuming code is code that must wait for the result.</p>
<p>So if we consume a promise, this means that when we make a request, we wait for the result. Then after result arrives, we perform some operation on those results.</p>
<p>Let's continue using the above example to understand how we can consume a promise.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(response);
    <span class="hljs-keyword">return</span> response.json()
}).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(data);
})
</code></pre>
<p>We make a request to the country API. Then, after the fetch request, we use the <code>then()</code> method to consume the promise. After that, we return a bunch of information like header, status, and so on (you can see it in the below output image).</p>
<p>So we specifically need data which we need to convert to JSON which returns a promise. The data which is returned when we make a API request gets returned in the form of a promise.</p>
<p>To handle that promise, we again use the then() method to log data from the response. Using multiple <code>then()</code> methods on a single request is called <strong>chaining promises.</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/121212.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-handle-rejected-promises">How to Handle Rejected Promises</h2>
<p>Consuming promises is good and all, but it's also very important to learn how to handle rejected promises. In real world situations, there could be times when our app crashes due to not handling rejected promises properly.</p>
<p>So let's take an example: we will put our promises in a function called <code>call()</code>. In HTML, we will create a button and add an event listener to it. When we click on the button it will call the <code>call()</code> function.</p>
<p>Here's what that looks like:</p>
<p><code>index.html</code>:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Promises<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Request<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><code>script.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">call</span>(<span class="hljs-params"></span>)</span>{

    <span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(response);
        <span class="hljs-keyword">return</span> response.json()
    }).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(data);
    })

}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"button"</span>)
btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    call();
})
</code></pre>
<p>Why are we doing this? We are setting the promise up to get rejected. Once we run this code, go to inspect and select the network tab. Set No throttling to offline and click on the button to send the request. You will get a rejected promise.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/1111.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once we click on the button, we will get error which is caused by no internet connection.</p>
<p>This situation can happen in the real world if a user's internet connection is slow. We are making an API request for which we need internet with decent speed. Sometimes the client might have an issue with their internet. This can lead to rejected promises which will throw an error which we haven't seen how to handle yet.</p>
<p>Now we will learn to handle this error. We used then() to consume our promises. Similar to that, we will chain the <code>catch()</code> method to that promise. Take a look at the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">call</span>(<span class="hljs-params"></span>)</span>{

    <span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(response);
        <span class="hljs-keyword">return</span> response.json()
    }).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(data);
    }).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span>{
        alert(err);
    })

}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"button"</span>)
btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    call();
})
</code></pre>
<p>Now the <code>catch()</code> method will get an error from the rejected promise and will display the message in an alert.</p>
<p>We get the error because we got a rejected promise which indicates that there is some issue. We can do whatever we want in the catch() block when we encounter an error.</p>
<p>Along with the catch() method, there is one more helpful method called <code>finally()</code>. We can chain it to promises which will run no matter whether the promise is accepted or rejected.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">call</span>(<span class="hljs-params"></span>)</span>{

    <span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(response);
        <span class="hljs-keyword">return</span> response.json()
    }).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(data);
    }).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(err);
    }).finally(<span class="hljs-function">() =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Will always run"</span>);
    })

}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"button"</span>)
btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    call();
})
</code></pre>
<p>We can use this <code>finally()</code> method for clearing things after the API call. There are many ways to use the <code>finally()</code> method.</p>
<h2 id="heading-how-to-create-a-promise">How to Create a Promise</h2>
<p>We know how to consume promises, but what about creating your own promises? You can do that using <code>new Promise()</code>.</p>
<p>You might wonder - why do we need our own promises? Firstly, promises are asynchronous in nature. We can create any task to be asynchronous by creating our own promises. Wecan handle them using the <code>then()</code> and <code>catch()</code> methods that we learned in the above section.</p>
<p>Once you know how to create promises, you can make any piece of code asynchronous. Then it will not block code execution if the other code running is taking a long time to complete.</p>
<p>Let's see how this works using an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> lottery = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Lottery is happening"</span>);

    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span>(<span class="hljs-built_in">Math</span>.random() &gt;= <span class="hljs-number">0.5</span>){
            resolve(<span class="hljs-string">"You Won!!!"</span>)
        }
        <span class="hljs-keyword">else</span>{
            reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Better luck next time"</span>))
        }
    }, <span class="hljs-number">5000</span>);

})
</code></pre>
<p>First we created a promise using <code>new Promise()</code>. It will have a function with two arguments, <code>resolve</code> and <code>reject</code>.</p>
<p>We will call <code>resolve</code> when our task is successful, and <code>reject</code> when the task is unsuccessful. We will use the lottery terminology that I used to explain the concept of promises in the above section.</p>
<p>Let's say if <code>Math.random()</code> gives a value below or equal to 0.5, we will win the lottery. Otherwise we will lose the lottery. If the condition is not true, the code throws a new error for better understanding of the error in the console. So we can throw our own custom errors to the user for better understanding.</p>
<p>In the example above, if <code>Math.random()</code> is less than 0.5, that means the user lost the lottery. So we throw our custom error <code>Better luck next time</code> so that the user understands that they lost the lottery.</p>
<p>Now we will try to consume the promise that we created.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> lottery = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Lottery is happening"</span>);

    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {    
        <span class="hljs-keyword">if</span>(<span class="hljs-built_in">Math</span>.random() &gt;= <span class="hljs-number">0.5</span>){
            resolve(<span class="hljs-string">"You Won!!!"</span>)
        }
        <span class="hljs-keyword">else</span>{
            reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Better luck next time"</span>))
        }   
    }, <span class="hljs-number">5000</span>);

})

lottery.then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(response);
}).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(err);
})
</code></pre>
<p>We consume the promise using the <code>then()</code> method. It will print the response that we provided in <code>resolve()</code>. If the promise is rejected we will catch the error in the <code>catch()</code> method. The error will come from the <code>reject()</code> argument that we mentioned in our own promise.</p>
<h3 id="heading-how-to-consume-promises-using-asyncawait">How to Consume Promises using Async/await</h3>
<p>Consuming promises using the then() method can become messy sometimes. So we have an alternative method to consume promises called async/await.</p>
<p>Just keep in mind that async/await will be using the <code>then()</code> method behind the scenes to consume promises.</p>
<p>Why use async/await if we have the <code>then()</code> method? We use async/await because it's easy to use. If we start chaining methods to promises using the <code>then()</code> method the chain will be very long and gets complex with the addition of multiple then() methods. So async/await is simpler.</p>
<p>Here's how async/await works:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://cat-fact.herokuapp.com/facts'</span>)
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json()
    <span class="hljs-built_in">console</span>.log(data);
}
fetchAPI()
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"FIRST"</span>);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/123123.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the above code, we first call the fetchAPI() to see the async behavior of the function. Then it logs "FIRST". So according to asynchronous JavaScript, fetchAPI() should be running in the background and not block the execution of the code. As a result, "FIRST" logs and then the result of fetchAPI is displayed.</p>
<p>Now, if you want to handle asynchronous tasks in your functions, you have to make that function asynchronous using the async keyword before the function. Wherever promises are returned we have to use await before it to consume promises.</p>
<p>Now you might be thinking, how should we handle errors? For that we can use try...catch() to handle errors in async/await.</p>
<h1 id="heading-error-handling-with-trycatch">Error Handling with <code>try...catch()</code></h1>
<p>We can use <code>try...catch()</code> in vanilla JavaScript as well. But it can also help us handle errors in asynchronous JavaScript with async/await.</p>
<p><code>try...catch()</code> is similar to the <code>catch()</code> method in <code>then()</code> using the <code>catch()</code> chaining method. Here we will try the code in the <code>try</code> block. If that runs successfully then there is no problem.</p>
<p>But if the code in the <code>try</code> block has an error, we can catch it in the <code>catch</code> block. We can check for errors in the try block and throw our custom error which will be caught in <code>catch</code> block. Once we catch the error in the <code>catch</code> block we can do whatever we want when we encounter an error.</p>
<p>Let's see how it works with the code example we've been using.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">try</span>{
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://cat-fact.herokuapp.com/fact'</span>)
        <span class="hljs-keyword">if</span>(!res.ok){
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
        }
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json()
        <span class="hljs-built_in">console</span>.log(data);
    } <span class="hljs-keyword">catch</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
    }
}


fetchAPI()
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"FIRST"</span>);
</code></pre>
<p>First, we wrap the asynchronous code in a <code>try</code> block. Then in the <code>catch</code> block we log the error. In the try block, if <code>res.ok</code> is false we throw our custom error using <code>throw new Error</code> which <code>catch</code> will get. Then we log it to the console.</p>
<h1 id="heading-how-to-return-values-from-async-functions">How to Return Values from Async Functions</h1>
<p>So far, we've learned about asynchronous code, the <code>then()</code> and <code>catch()</code> methods, and handling asynchronous code with async/await. But what if we want to return a value from an async function using async/await?</p>
<p>When you're working with asynchronous code, it's often necessary to return a value from an <code>async</code> function so that other parts of your program can use the result of the asynchronous operation.</p>
<p>For example, if you're making an HTTP request to fetch data from an API, you'll want to return the response data to the calling function so that it can be processed or displayed to the user.</p>
<p>Well, we can do that. Take a look at the below example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">try</span>{
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://cat-fact.herokuapp.com/facts'</span>)
        <span class="hljs-keyword">if</span>(!res.ok){
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
        }
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json()
        <span class="hljs-built_in">console</span>.log(data);
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Done with fetchAPI"</span>
    } <span class="hljs-keyword">catch</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
    }
}


<span class="hljs-built_in">console</span>.log(fetchAPI())
</code></pre>
<p>If we log the fetchAPI we will get back a promise which is fullfilled. You know very well how to handle these promises. We will be doing it using the <code>then()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">try</span>{
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://cat-fact.herokuapp.com/facts'</span>)
        <span class="hljs-keyword">if</span>(!res.ok){
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
        }
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json()
        <span class="hljs-built_in">console</span>.log(data);
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Done with fetchAPI"</span>
    } <span class="hljs-keyword">catch</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
    }
}


fetchAPI().then(<span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(msg);
}).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(err);
})
</code></pre>
<p>Now when we run our program, we will see our returned msg from the <code>try</code> block using async/await logged in the console.</p>
<p>But what if there was an error in async/await? The fetchAPI with the then() method will still log it and it would be undefined.</p>
<p>To avoid this in the catch block again we throw a new error and use the catch() method to catch that error after the then() method.</p>
<p>Try changing the <code>then()</code> and <code>catch()</code> methods with async/await. This would be a good exercise for you to understand what you've learned in this article.</p>
<p>In JavaScript, there are two common ways to work with asynchronous operations: <code>then/catch</code> method chaining and <code>async/await</code>. Both methods can be used to handle promises, which are objects that represent the eventual completion (or failure) of an asynchronous operation.</p>
<p><code>then/catch</code> method chaining is a more traditional way to handle asynchronous operations, while <code>async/await</code> is a newer syntax that provides a more concise and easier-to-read alternative.</p>
<h2 id="heading-how-to-run-promises-in-parallel">How to Run Promises in Parallel</h2>
<p>Let's say we want to make three requests for three different country capitals. We can do three different fetch calls, each of which will wait for the one above to complete.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">country1,country2,country3</span>)</span>{
    <span class="hljs-keyword">try</span>{
        <span class="hljs-keyword">const</span> res1 = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://restcountries.com/v3.1/name/<span class="hljs-subst">${country1}</span>`</span>)
        <span class="hljs-keyword">const</span> res2 = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://restcountries.com/v3.1/name/<span class="hljs-subst">${country2}</span>`</span>)
        <span class="hljs-keyword">const</span> res3 = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://restcountries.com/v3.1/name/<span class="hljs-subst">${country3}</span>`</span>)


        <span class="hljs-keyword">const</span> data1 = <span class="hljs-keyword">await</span> res1.json()
        <span class="hljs-keyword">const</span> data2 = <span class="hljs-keyword">await</span> res2.json()
        <span class="hljs-keyword">const</span> data3 = <span class="hljs-keyword">await</span> res3.json()
        <span class="hljs-built_in">console</span>.log(data1[<span class="hljs-number">0</span>].capital[<span class="hljs-number">0</span>]);
        <span class="hljs-built_in">console</span>.log(data2[<span class="hljs-number">0</span>].capital[<span class="hljs-number">0</span>]);
        <span class="hljs-built_in">console</span>.log(data3[<span class="hljs-number">0</span>].capital[<span class="hljs-number">0</span>]);
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Done with fetchAPI"</span>
    } <span class="hljs-keyword">catch</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
    }
}


fetchAPI(<span class="hljs-string">"canada"</span>, <span class="hljs-string">"germany"</span>, <span class="hljs-string">"russia"</span>)
</code></pre>
<p>In the above code, we are making three fetch calls, then converting them to json() and logging their capitals.</p>
<p>But if you hit inspect and see in the network tab, res2 is waiting for res1 to complete and res3 is waiting for res2 to complete.</p>
<p>This can negatively impact our application's performance. Because if a promise is waiting for another promise to complete it can negatively impact the performance of the website.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/321.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To overcome this performance issue, we can use something called <code>**Promise.all**</code> . It will call three fetch requests simultaneously, which in return will reduce our fetching time and improve our application's performance.</p>
<h2 id="heading-how-to-use-promiseall">How to Use Promise.all()</h2>
<p>With the help of Promise.all(), we can run multiple promises in parallel which will boost performance. The promise.all() takes an array as an argument which are promises and run them in parallel.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> promise1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
       resolve(<span class="hljs-string">"First Promise"</span>)
    }, <span class="hljs-number">2000</span>)
})

<span class="hljs-keyword">let</span> promise2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"Second Promise"</span>)

<span class="hljs-keyword">let</span> returnedPromises = <span class="hljs-built_in">Promise</span>.all([promise1,promise2]).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(res);
})
</code></pre>
<p>The result of using promise.all() is that both promises were running in parallel.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/2121.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>After reading this tutorial, I hope you have a better understanding of asynchronous JavaScript. Feel free to reach out to me for discussion and suggestions.</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
<li><p><a target="_blank" href="https://www.instagram.com/kedar_98/">Instagram</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous Programming in JavaScript for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article we're going to take a look at a key topic when it comes to programming: managing asynchronism. We'll start by giving a theoretical foundation about what asynchronism is, and how it relates to key components of JavaScript:... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronism-in-javascript/</link>
                <guid isPermaLink="false">66d45eead1ffc3d3eb89dde1</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Mon, 13 Feb 2023 16:15:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-giallo-859895.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article we're going to take a look at a key topic when it comes to programming: managing asynchronism.</p>
<p>We'll start by giving a theoretical foundation about what asynchronism is, and how it relates to key components of JavaScript: The execution thread, the call stack and the event loop.</p>
<p>And then I'm going to present the three ways in which we can handle asynchronous tasks in JavaScript: Callbacks, promises and async/await.</p>
<p>Sounds fun, right? Let's go!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-asynchronism">What is asynchronism</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-asynchronism-in-javascript">Asynchronism in Javascript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-the-call-stack">What is the call stack?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-web-apis-the-callback-queue-and-the-event-loop">Web APIs, the callback queue, and the event loop</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-web-apis">What are Web APIs?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-the-callback-queue-and-the-event-loop">What are the callback queue and the event loop?</a></p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-so-how-do-we-code-this-stuff">So how do we code this stuff... ?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-callback-functions-work">How callback functions work</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-promises-work">How promises work</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-async-await-works">How async-await works</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrap-up">Wrap-up</a></p>
</li>
</ul>
<h1 id="heading-what-is-asynchronism">What is Asynchronism?</h1>
<p>Any computer program is nothing but a series of tasks we require the computer to execute. In JavaScript, tasks can be classified into <strong>synchronous</strong> and <strong>asynchronous</strong> types.</p>
<p><strong>Synchronous</strong> tasks are the ones that <strong>execute sequentially</strong>, one after the other, and while they're being executed nothing else is being done. At each line of the program, the browser waits for the task to finish before jumping to the next one.</p>
<p>We say this kind of tasks are <strong>"blocking"</strong>, because while they execute they block the execution thread (I'm going to explain what this is in a sec), preventing it from doing anything else.</p>
<p><strong>Asynchronous</strong> tasks, on the other hand, are the ones that, while they execute, they don't block the execution thread. So the program can still perform other tasks while the asynchronous task is being executed.</p>
<p>This is why we say this kind of tasks are <strong>"non blocking"</strong>. This technique comes in handy specially for tasks that take long time to execute, as by not blocking the execution thread the program is able to execute more efficiently.</p>
<p>According to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing">Mozilla docs</a>:</p>
<blockquote>
<p><strong>Asynchronous programming</strong> is a technique that enables your program to start a potentially <strong>long-running</strong> task and still be able to <strong>be responsive to other events while that task runs</strong>, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result.</p>
</blockquote>
<h1 id="heading-asynchronism-in-javascript">Asynchronism in JavaScript</h1>
<p>Now that we have a more or less clear idea of what asynchronism is, let's get into the complicated interesting stuff – how JavaScript makes this possible.</p>
<p>One of the first apparent paradoxes of JavaScript – and there are a few – that you'll encounter when learning about the language is that JavaScript is a <strong>single threaded</strong> language.</p>
<p>"Single threaded" means it has a single thread of execution. This means that JavaScript programs can only execute a single task at a time.</p>
<p>This isn't the case, for example, for languages like Java or Ruby, which can create various execution threads and in that way execute many tasks simultaneously.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Untitled-Diagram.drawio--3-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Visualizing single thread vs multi thread execution</em></p>
<p>And here the paradox is: if JavaScript can only execute only one task at a time, how come synchronous tasks can execute while asynchronous tasks complete "in the background"? How come asynchronous tasks don't block the execution thread? How are they executed then?</p>
<p>To explain this, we need to briefly describe how web browsers execute JavaScript code and some of its core components: The call stack, web APIs, the callback queue, and the event loop.</p>
<h2 id="heading-what-is-the-call-stack">What is the Call Stack?</h2>
<p>As you may now, a stack is a type of data structure where elements are added and removed following a LIFO (last in, first out) pattern. Browsers use something called the <strong>call stack</strong> to read and execute each task contained in a Javascript program.</p>
<p>Side comment: If you're not familiar with data structures, you can take a look at <a target="_blank" href="https://www.freecodecamp.org/news/data-structures-in-javascript-with-examples/">this article I wrote a while ago.</a></p>
<p>The way it works is quite simple. When a task is to be executed, it's added to the call stack. When it's finished, it's removed from the call stack. This same action is repeated for each and every task until the program is fully executed.</p>
<p>Let's see this with an easy example. If we had these three lines of code:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'task 1'</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'task 2'</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'task 3'</span>)
</code></pre>
<p>Our call stack would look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Untitled-Diagram.drawio--1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Illustration of an example call stack</em></p>
<ol>
<li><p>Call stack starts off empty at the start of the program.</p>
</li>
<li><p>The first task is added to the call stack and executed.</p>
</li>
<li><p>The first task is removed from the call stack once finished.</p>
</li>
<li><p>The second task is added to the call stack and executed.</p>
</li>
<li><p>The second tasks is removed from the call stack once finished.</p>
</li>
<li><p>The third task is added to the call stack and executed.</p>
</li>
<li><p>The third task is removed from the call stack once finished. End of the program.</p>
</li>
</ol>
<p>Easy right? Now let's see a slightly more complicated example with these lines of code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> multiply = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a*b

<span class="hljs-keyword">const</span> square = <span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> multiply(n, n)

<span class="hljs-keyword">const</span> printSquare = <span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(square(n))

printSquare(<span class="hljs-number">4</span>)
</code></pre>
<p>Here we're calling <code>printSquare()</code>, which itself calls <code>square()</code>, which itself calls <code>multiply()</code>. With this program, our call stack might look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Untitled-Diagram.drawio.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Another more complex example of a call stack</em></p>
<ol>
<li><p>Call stack starts off empty at the start of the program.</p>
</li>
<li><p><code>printSquare(4)</code> is added to the call stack and executed.</p>
</li>
<li><p>As <code>printSquare(4)</code> calls the function <code>square(4)</code>, <code>square(4)</code> is added to the call stack and executed as well. Note that as the execution of <code>printSquare(4)</code> isn't finished yet, it's kept on the stack.</p>
</li>
<li><p>As <code>square(4)</code> calls <code>multiply(4,4)</code>, <code>multiply(4,4)</code> is added to the call stack and executed as well.</p>
</li>
<li><p><code>multiply(4,4)</code> is removed from the call stack once finished.</p>
</li>
<li><p><code>square(4)</code> is removed from the call stack once finished.</p>
</li>
<li><p><code>printSquare(4)</code> is removed from the call stack once finished. End of the program.</p>
</li>
</ol>
<p>In this example we can clearly see the <strong>LIFO pattern</strong> the call stack uses to add and remove tasks to it.</p>
<p>The important thing to notice here is that tasks are <strong>not removed from the stack until they're finished</strong>. This is how <strong>synchronous callbacks</strong> work.</p>
<p>When a function calls another function, the callback is added to the stack and executed. Once the execution of the callback is completed, it's removed from the stack and the execution of the main function is completed.</p>
<h2 id="heading-web-apis-the-callback-queue-and-the-event-loop">Web APIs, the Callback Queue, and the Event Loop</h2>
<p>So far so good, right? Using the call stack, JavaScript takes account of each task, executes it, and then moves on to the next. Fairly simple.</p>
<p>Now let's check the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'task1'</span>)

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'task2'</span>), <span class="hljs-number">0</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'task3'</span>)
</code></pre>
<p>Here, we're logging three separate strings, and on the second one we're using <code>setTimeout</code> to log it after 0 milliseconds. Which should be, according to common logic, instantly. So one should expect the console to log: "task1", then "task2", and then "task3".</p>
<p>But that's not what happens:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-23.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And if we had a look at our call stack during the program, It would look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Untitled-Diagram.drawio--2-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ol>
<li><p>Call stack starts off empty at the start of the program.</p>
</li>
<li><p><code>console.log('task1')</code> is added to the call stack and executed.</p>
</li>
<li><p><code>console.log('task1')</code> is removed from the call stack once finished.</p>
</li>
<li><p><code>setTimeout(console.log('task2'))</code> is added to the call stack, but <strong>it's not executed</strong>.</p>
</li>
<li><p><code>setTimeout(console.log('task2'))</code> <strong>"mysteriously"</strong> disappears from the call stack.</p>
</li>
<li><p><code>console.log('task3')</code> is added to the call stack and executed.</p>
</li>
<li><p><code>console.log('task4')</code> is removed from the call stack once finished.</p>
</li>
<li><p><code>console.log('task2')</code> <strong>"mysteriously"</strong> hops into the call stack and is executed.</p>
</li>
<li><p><code>console.log('task2')</code> is removed from the call stack once finished.</p>
</li>
</ol>
<p>To explain this "<strong>mysterious</strong>" disappearance and reappearance of the <code>setTimeout</code> task, we need to introduce three more components that are part of the browser runtime: <strong>Web APIs, the callback queue, and the event loop.</strong></p>
<h3 id="heading-what-are-web-apis">What are Web APIs?</h3>
<p>Web APIs are a set of features and functionalities that the browser uses to enable JavaScript to execute. These features include DOM manipulation, AJAX calls, and <code>setTimeout</code> among other things.</p>
<p>To simplify the understanding of this, think about it like a different "execution place" rather than the call stack. When the call stack detects that the task it's processing is web API-related, it asks the web API "Hey API, I need to get this done", and the web API takes care of it, allowing the call stack to continue with the next task in the stack.</p>
<h3 id="heading-what-are-the-callback-queue-and-the-event-loop">What are the callback queue and the event loop?</h3>
<p>In the code example we saw before, we saw that <code>setTimeout(console.log('task2'))</code> <strong>"mysteriously"</strong> disappeared from the call stack. We now know that, it didn't actually disappear – it was sent to the web API.</p>
<p>But then it <strong>"mysteriously"</strong> reappeared again, so how does that work? Well, that's the job of the callback queue and the event loop.</p>
<p>The <strong>callback queue</strong> is a queue that stores the tasks that the web APIs return. Once the web API finishes executing the given task (which in this case was processing the <code>setTimeout</code>) it sends the callback to the callback queue.</p>
<p>Queues are a type of data structure where elements are added and removed following a FIFO pattern (first in, first out). Again, if you're not familiar with data structures, you can <a target="_blank" href="https://www.freecodecamp.org/news/data-structures-in-javascript-with-examples/">take a look at this article.</a></p>
<p>The <strong>event loop</strong> is a loop (woah... really?) that constantly checks two things:</p>
<ol>
<li><p>If the call stack is empty</p>
</li>
<li><p>If there's any task present in the callback queue</p>
</li>
</ol>
<p>If both of these conditions are met, then the task present in the callback queue is sent to the call stack to complete its execution.</p>
<p>Now that we know about web APIs, the callback queue, and the event loop, we can know what actually happened in our previous example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Untitled-Diagram.drawio--4--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Following the red lines, we can see that when the call stack identified that the task involved <code>setTimeout</code>, it sent it to the web APIs to process it.</p>
<p>Once the web APIs processed the task, it inserted the callback into the callback queue.</p>
<p>And once the event loop detected that the call stack was empty and that there was a callback present in the callback queue, it inserted the callback in the call stack to complete its execution.</p>
<p>This is how JavaScript makes asynchronism possible. Asynchronous tasks are processed by web APIs instead of the call stack, which handles only synchronous tasks.</p>
<p>In this way, the call stack can just derive asynchronous tasks to web APIs and carry on executing whatever else is present on the stack. And thanks to the callback queue and the event loop, once the asynchronous task was handled by the web APIs, the callback is reinserted into the call stack.</p>
<p>It's important to remember that JavaScript always runs only one task at a time. The "magic" of asynchronism is made possible by the existence of the web APIs, the callback queue, and the event loop, which are responsible for managing asynchronous tasks.</p>
<p>Side comment: If you wonder how all this works on Node instead of a browser, it's fairly similar. Instead of web APIs you have C++ APIs. The call stack, the callback queue, and the event loop work exactly the same.</p>
<p>If you want a more detailed explanation of all these topics, I recommend that you take a look at <a target="_blank" href="https://www.youtube.com/watch?v=8aGhZQkoFbQ&amp;t=1s">this very well known talk by Philip Roberts</a>.</p>
<h1 id="heading-so-how-do-we-code-this-stuff">So How Do We Code This Stuff... ?</h1>
<p>Now that we have the theoretical foundation of how JavaScript makes asynchronism possible, let's see how all this implements in code.</p>
<p>There are mainly three ways in which we can code asynchronism in JavaScript: callback functions, promises, and async-await.</p>
<p>I'll present them in the chronological order JavaScript has provided these features (first there were only callback functions, then came promises, and lastly async-await). But keep in mind that the most common and recommended practice nowadays is to use async-await. ;)</p>
<h2 id="heading-how-callback-functions-work">How Callback Functions Work</h2>
<p>Callbacks are functions that are passed as arguments to other functions. The function that takes the argument is called a "Higher order function", and the function that is passed as an argument is called a "Callback".</p>
<p>We can see this in practice in the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> callbackFunc = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Im the callback'</span>)

<span class="hljs-keyword">const</span> higherOrderFunction = <span class="hljs-function"><span class="hljs-params">callback</span> =&gt;</span> callback()

higherOrderFunction(callbackFunc)
</code></pre>
<p>Side comment: the possibility of passing functions as parameters to other functions is one of the features that make functions <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function"><strong>first class citizens</strong> in JavaScript</a>.</p>
<p>The difference between synchronous and asynchronous callbacks relies on the type of task that function executes. There's no syntactic difference between each kind. Let's see this in code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'logging...'</span>)
arr.map(<span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'sync item'</span>, e)) <span class="hljs-comment">// This is a synchronous callback</span>

arr.map(<span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'async item'</span>, e), <span class="hljs-number">0</span>)) <span class="hljs-comment">// This is an asynchronous callback</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'the stuff'</span>)
</code></pre>
<p>Here we have an array of three elements, a couple of <code>console.log</code>s, and two <code>map</code> functions. What <code>map</code> does is iterate over each element of the array and perform a function for each element in the array. That function is defined as a callback.</p>
<p>In the first <code>map</code>, we are logging the item with <code>console.log</code>. In the second one, we're doing the same but using <code>setTimeout</code> (which as we saw before is an asynchronous task performed by web APIs).</p>
<p>As a result, our console will look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-55.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>First, all the synchronous callbacks are executed, and then the asynchronous callbacks kick in.</p>
<p>As we can see, the fact that the functions execute asynchronously isn't related to the fact that they're callbacks or not, but rather to the kind of task that function executes. As <code>setTimeout</code> is an async task, those callbacks are executed asynchronously.</p>
<h2 id="heading-how-promises-work">How Promises Work</h2>
<p>A more modern approach for dealing with asynchronism is by using promises. A promise is a special kind of object in JavaScript that has 3 possible states:</p>
<ul>
<li><p><strong>Pending:</strong> It's the initial state, and it signifies that the corresponding task is yet to be resolved.</p>
</li>
<li><p><strong>Fulfilled:</strong> Means the task has been completed successfully.</p>
</li>
<li><p><strong>Rejected:</strong> Means the task has produced some kind of error.</p>
</li>
</ul>
<p>To see this in practice, we'll use a realistic case in which we fetch some data from an API endpoint and log that data in our console. We'll use the <code>fetch</code> API provided by browsers and a public API that returns Chuck Norris jokes.</p>
<p>Here our function executes a GET HTTP request to the endpoint, and we use the <code>then</code> and <code>catch</code> methods that the promise object has to process the promise response.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchJokeWithPromises = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fetching with promises...'</span>)

    fetch(<span class="hljs-string">'https://api.chucknorris.io/jokes/random'</span>)
        .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
        .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'res'</span>, res))
        .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'There was an error!'</span>, error))
}

fetchJokeWithPromises()
</code></pre>
<p>But let's take a closer look at this step by step.</p>
<ul>
<li>If we log just the fetch line, like this:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fetch'</span>, fetch(<span class="hljs-string">'https://api.chucknorris.io/jokes/random'</span>))
</code></pre>
<p>We see we get a promise with a pending state:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-56.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Then if we execute the first <code>then</code> method and log its result, we get the following:</li>
</ul>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.chucknorris.io/jokes/random'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'res'</span>, res))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-57.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We see here we no longer have a promise, but the actual response from the endpoint. The <code>then</code> method waits for the promise to complete, and then provides us with the result, which is present as a parameter for the method.</p>
<ul>
<li>But to read the actual response body (which in our console we can see its a <code>ReadableStream</code>), we have to call <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Response/json">the <code>.json()</code> method on it</a>. This itself returns another promise. That's why we need another <code>.then()</code>.</li>
</ul>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.chucknorris.io/jokes/random'</span>)
        .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
        .then(<span class="hljs-function"><span class="hljs-params">responseBody</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'responseBody'</span>, responseBody))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-58.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And here, finally we can see the full response and our joke in the <code>value</code> property. ;)</p>
<ul>
<li>What the <code>catch</code> method does is execute whenever a promise is rejected. Normally <code>catch</code> is used to handle an error, like showing a certain message to the user when an API fails to respond.</li>
</ul>
<p>To see it in action, let's use a random endpoint like this one:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://asdadsasdasd/'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
    .then(<span class="hljs-function"><span class="hljs-params">resp</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'resp'</span>, resp))
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'There was an error!'</span>, error))
</code></pre>
<p>And in our console we can see the <code>catch</code> method executed:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-59.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>An important thing to notice is in situations like this one, where we have various <code>.then</code> methods chained, we only need to use one <code>.catch</code> method. This is because that one <code>.catch</code> will process the errors in all of the promises chained.</p>
<p>Again, to see this in action now, let's go back to our previous endpoint and mess with the <code>.json()</code> call, misspelling it now.</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.chucknorris.io/jokes/random'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.jon())
    .then(<span class="hljs-function"><span class="hljs-params">resp</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'resp'</span>, resp))
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'There was an error!'</span>, error))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-60.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To round up promises, there's an additional method provided by promises which is <code>.finally</code>. This will execute always once the promise has been resolved, either successfully or not.</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.chucknorris.io/jokes/random'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
    .then(<span class="hljs-function"><span class="hljs-params">resp</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'resp'</span>, resp))
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'There was an error!'</span>, error))
    .finally(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Promised resolved!'</span>))
</code></pre>
<h2 id="heading-how-async-await-works">How Async-Await Works</h2>
<p>Async-await is the latest way of dealing with asynchronism provided by JavaScript. Basically, it's just syntactic sugar that allow us to deal with promises in a more concise way than using <code>.then</code> methods.</p>
<p>Let's see this in action following the same previous example.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchJokeWithAsyncAwait = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.chucknorris.io/jokes/random'</span>)
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json()
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'async-await data'</span>, data)

    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'There was an error!'</span>, error)
    }
}

fetchJokeWithAsyncAwait()
</code></pre>
<p>Here we have a function that executes the fetch and logs the response. See that we start by using the <code>async</code> keyword when we declare the function. This is a requirement for all functions that use async-await.</p>
<p>Then we enclose our fetch call in a <code>try-catch</code> statement. This is required because with async-await we won't use the <code>.catch</code> method. But we still need to process possible errors.</p>
<p>We achieve this with the use of <code>try-catch</code>. If anything contained in the <code>try</code> statement returns an error, then the <code>catch</code> statement executes, obtaining the error as a parameter.</p>
<p>As you can see, we are assigning the result of the <code>fetch</code> call to a variable called <code>res</code>. And before the <code>fetch</code> we're using the <code>await</code> keyword.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.chucknorris.io/jokes/random'</span>)
</code></pre>
<p>This means that Javascript will wait for the promise to resolve before assigning its value to the variable. And any operations done on that variable, will only execute once its value has been assigned.</p>
<p>In the next line we're calling the <code>.json()</code> method on the <code>res</code> variable, and again using the <code>await</code> keyword before it so the promise result is then assigned to the <code>data</code> variable.</p>
<p>And lastly, we log our <code>data</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-62.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As mentioned, async-await is just syntactic sugar. It doesn't do anything differently than <code>.then</code> and <code>.catch</code> methods. It's just easier to write and read.</p>
<h1 id="heading-wrap-up">Wrap-up</h1>
<p>Well everyone, as always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/were-out-of-time-out-of-time.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous Programming in JavaScript – Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ To understand what asynchronous programming means, think about multiple people working on a project simultaneously, each on a different task. In traditional (synchronous) programming, each person would have to wait for the person before them to finis... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-programming-in-javascript/</link>
                <guid isPermaLink="false">66bd9047abf0ccf74f1ce9a3</guid>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Boateng Dickson ]]>
                </dc:creator>
                <pubDate>Tue, 31 Jan 2023 23:17:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/Asynchronous-programming.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>To understand what asynchronous programming means, think about multiple people working on a project simultaneously, each on a different task.</p>
<p>In traditional (synchronous) programming, each person would have to wait for the person before them to finish their task before starting their own. </p>
<p>But with asynchronous programming, everyone can start and work on their tasks simultaneously without waiting for the others to finish.</p>
<p>Similarly, in a computer program, asynchronous programming allows a program to work on multiple tasks simultaneously instead of completing one task before moving on to the next one. This can make the program get more things done in a shorter amount of time.</p>
<p>For example, a program can send a request to a server while handling user input and processing data, all at the same time. This way, the program can run more efficiently.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-321.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In this article, we will delve into the world of asynchronous programming in JavaScript, exploring the different techniques and concepts that are used to achieve this powerful programming paradigm. </p>
<p>From callbacks to promises and async/aawait, you will understand how to harness the power of asynchronous programming in your JavaScript projects.</p>
<p>Understanding asynchronous programming is essential for building high-performance web applications, whether you're a seasoned developer or just getting started with JavaScript. So, read on to learn more about this vital concept.</p>
<h2 id="heading-what-is-synchronous-programming">What is Synchronous Programming?</h2>
<p>Synchronous programming is a way for computers to do things one step at a time, in the order they are given the instructions. </p>
<p>Imagine you're cooking dinner and have a list of tasks, like boiling water for pasta, frying chicken, and making a salad.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-343.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You would do these tasks one at a time and wait for each one to finish before moving to the next. </p>
<p>Synchronous programming works similarly, where the computer will complete one task before moving on to the next. This makes it easy to understand and predict what the computer will do at any given time.</p>
<p>Here's an example of synchronous code in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Define three functions</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">firstTask</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Task 1"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">secondTask</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Task 2"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">thirdTask</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Task 3"</span>);  
}

<span class="hljs-comment">// Execute the functions</span>
firstTask();
secondTask();
thirdTask();
</code></pre>
<p>This code will output the following messages in the order they appear:</p>
<pre><code><span class="hljs-string">"Task 1"</span>
<span class="hljs-string">"Task 2"</span>
<span class="hljs-string">"Task 3"</span>
</code></pre><p>The code will execute the tasks in the order you see them and wait for each task to be completed before moving on to the next one.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-244.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram showing how synchronous programming works.</em></p>
<p>However, synchronous programming can be problematic in certain situations, particularly when dealing with tasks that take a significant amount of time to complete.</p>
<p>For example, let's say that a synchronous program performs a task that requires waiting for a response from a remote server. The program will be stuck waiting for the response and cannot do anything else until the response is returned. This is known as <em>blocking</em>, and it can lead to an application appearing unresponsive or "frozen" to the user.</p>
<p>Consider the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someLongRunningFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> start = <span class="hljs-built_in">Date</span>.now();
    <span class="hljs-keyword">while</span> (<span class="hljs-built_in">Date</span>.now() - start &lt; <span class="hljs-number">5000</span>) {
        <span class="hljs-comment">// do nothing</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello"</span>;
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Starting...'</span>);

<span class="hljs-keyword">let</span> result = someLongRunningFunction();
<span class="hljs-built_in">console</span>.log(result);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'...Finishing'</span>);
</code></pre>
<p>In this example:</p>
<ul>
<li>The program starts by logging <em>"Starting..."</em> to the console.</li>
<li>Then it calls the <code>someLongRunningFunction</code>, which simulates a long-running task that takes 5 seconds to complete. This function will block the execution of the rest of the program while it runs. </li>
<li>Once the function completes, it will return <em>"Hello"</em>, and the program will log it on the console.</li>
<li>Finally, the program will log <em>"Finishing"</em> to the console.</li>
</ul>
<p>During the 5 seconds that <code>someLongRunningFunction()</code> is being executed, the program will be blocked, become unresponsive, and be unable to execute the next line of code. This can cause the program to take a long time to complete and make the application unresponsive to the user.</p>
<p>However, if the program is executed asynchronously, it will continue to run the next line of code instructions rather than becoming blocked. This will enable the program to remain responsive and execute other code instructions while waiting for the timeout to complete.</p>
<h2 id="heading-what-is-asynchronous-programming">What is Asynchronous Programming?</h2>
<p>Asynchronous programming is a way for a computer program to handle multiple tasks simultaneously rather than executing them one after the other. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-336.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram showing how asynchronous programming works.</em></p>
<p>Asynchronous programming allows a program to continue working on other tasks while waiting for external events, such as network requests, to occur. This approach can greatly improve the performance and responsiveness of a program.</p>
<p>For example, while a program retrieves data from a remote server, it can continue to execute other tasks such as responding to user inputs. </p>
<p>Here's an example of an asynchronous program using the <code>setTimeout</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Start of script"</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"First timeout completed"</span>);
}, <span class="hljs-number">2000</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"End of script"</span>);
</code></pre>
<p>In this example, the <code>setTimeout</code> method executes a function after a specified time. The function passed to <code>setTimeout</code> will be executed asynchronously, which means that the program will continue to execute the next line of code without waiting for the timeout to complete.</p>
<p>When you run the code, the output will be:</p>
<pre><code>Start <span class="hljs-keyword">of</span> script
End <span class="hljs-keyword">of</span> script
First timeout completed
</code></pre><p>As you can see, <code>console.log("First timeout completed")</code> will be executed after 2 seconds. Meanwhile, the script continues to execute the next code statement and doesn't cause any "blocking" or "freezing" behaviour.</p>
<p>In JavaScript, asynchronous programming can be achieved through a variety of techniques. One of the most common methods is the use of <em>callbacks</em>.</p>
<h2 id="heading-how-to-use-a-callback-function">How to Use a Callback Function</h2>
<p>Let's say you want to plan a birthday party for your child. You have to invite the guests, order a cake, and plan the games. But you also want to hire a clown to entertain the guests. You can only have the clown come to the party once all the other party arrangements are done, and the guests have arrived.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-341.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration of a clown</em></p>
<p>So, you tell the clown to come to the party only after you have notified him that the guests have arrived. In this case, the clown represents a callback function, and the "guests arriving" represents the function that has to complete execution before the callback can be executed.</p>
<p>In code, a callback function is a function that is passed as an argument to another function, and it is executed after the first function has finished running. It's commonly used in JavaScript to handle asynchronous operations like fetching data from a server, waiting for a user's input, or handling events.</p>
<p>Here is a simple example of how you can use a callback function to handle an asynchronous operation:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Declare function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> data = {<span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>};
    callback(data);
  }, <span class="hljs-number">3000</span>);
}

<span class="hljs-comment">// Execute function with a callback</span>
fetchData(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) </span>{
  <span class="hljs-built_in">console</span>.log(data);
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Data is being fetched..."</span>);
</code></pre>
<p>In this example:</p>
<ul>
<li>We have a function called <code>fetchData</code> that uses the <code>setTimeout</code> method to simulate an asynchronous operation. The function takes a callback as an argument.</li>
<li>The callback function is then passed the data retrieved by the function after the timeout has been completed.</li>
</ul>
<p>The <code>setTimeout</code> method is used to execute the callback after a specified time (in this case, 3 seconds). The callback will be executed asynchronously, which means that the program will continue to execute the next line of code without waiting for the timeout to complete.</p>
<p>When you run the code, the output will be:</p>
<pre><code>Data is being fetched...
{<span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>}
</code></pre><p>As you can see, <code>console.log("First timeout completed")</code> will be executed after 3 seconds. Meanwhile, the script continues to execute the next statement, <code>console.log("Data is being fetched...");</code>. </p>
<p>This is the core concept of asynchronous programming. The script doesn't wait for the asynchronous operation to complete. It just continues to execute the next instruction.</p>
<h2 id="heading-what-is-callback-hell">What is Callback Hell?</h2>
<p>Callbacks provide a useful way to handle asynchronous operations. However, when many callbacks are nested, the code can be complex and hard to read and understand. </p>
<p>This happens when you chain multiple callbacks together, one after the other, creating a pyramid-like structure of indentation called callback hell, also known as the "Pyramid of Doom".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-340.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is an example of callback hell:</p>
<pre><code class="lang-javascript">getData(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a</span>) </span>{
  getMoreData(a, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">b</span>) </span>{
    getEvenMoreData(b, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">c</span>) </span>{
      getEvenEvenMoreData(c, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">d</span>) </span>{
        getFinalData(d, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">finalData</span>) </span>{
          <span class="hljs-built_in">console</span>.log(finalData);
        });
      });
    });
  });
});
</code></pre>
<p>In this example:</p>
<ol>
<li>The <code>getData</code> function takes a callback as an argument and is executed after data is retrieved.</li>
<li>The callback function then takes the data and calls the <code>getMoreData</code> function, which also takes a callback as an argument, and so on.</li>
</ol>
<p>This nesting of callbacks can make the code difficult to maintain, and the indentation makes it even harder to see the overall structure of the code.</p>
<p>To avoid callback hell, you can use a more modern way of handling async operations known as promises. Promises provide a more elegant way of handling the asynchronous flow of a program compared to callback functions. This is the focus of the next section.</p>
<h2 id="heading-how-do-promises-work">How Do Promises Work?</h2>
<p>A promise represents a way of handling asynchronous operations in a more organized way. It serves the same purpose as a callback but offers many additional capabilities and a more readable syntax.</p>
<p>A promise in JavaScript is a placeholder for a future value or action. By creating a promise, you are essentially telling the JavaScript engine to "promise" to perform a specific action and notify you once it is completed or fails.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-339.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration of a promise and the JS engine</em></p>
<p>Next, callback functions are then attached to the promise to handle the outcome of the action. These callbacks will be invoked when the promise is fulfilled (action completed successfully) or rejected (action failed).</p>
<p>As a JavaScript developer, you will likely spend more time consuming promises returned by asynchronous Web APIs and managing their outcomes rather than creating them yourself. </p>
<h3 id="heading-how-to-create-a-promise">How to Create a Promise</h3>
<p>To create a promise<em>,</em> you'll create a new instance of the <code>Promise</code> object by calling the <code>Promise</code> constructor.</p>
<p>The constructor takes a single argument: a function called <code>executor</code>. The "executor" function is called immediately when the promise is created, and it takes two arguments: a <code>resolve</code> function and a <code>reject</code> function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-345.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram of the anatomy of a promise.</em></p>
<p>Write the following line of code to declare a promise:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Initialize a promise</span>
<span class="hljs-keyword">const</span> myPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) =&gt; </span>{})
</code></pre>
<p>Now, let's inspect the <code>myPromise</code> object by logging it to the console.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(myPromise);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/promise-object.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>This image represents an output of inspecting the <code>promise</code> object.</em></p>
<p>As you can see, the promise has a <em>pending</em> status and an <em>undefined</em> value. This is because nothing has been set up for the promise object yet, so it's going to sit there in a pending state forever without any value or result.</p>
<p>Now, let's set up <code>myPromise</code> to resolve with a string printed to the console after 2 seconds.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        resolve(<span class="hljs-string">"Hello from the promise!"</span>);
    }, <span class="hljs-number">2000</span>);
});
</code></pre>
<p>Now, when you inspect <code>myPromise</code> object, you'll find that it has a status of <em>"fulfilled</em>", and a value set to the string you passed to the <code>resolve</code> function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/myPromise-obj.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A promise has three states:</p>
<ul>
<li><strong>Pending:</strong> initial state, neither fulfilled nor rejected.</li>
<li><strong>Fulfilled:</strong> meaning that an operation was completed successfully.</li>
<li><strong>Rejected:</strong> meaning that an operation failed.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-347.png" alt="Image" width="600" height="400" loading="lazy">
<em>Pending, fulfilled, and rejected states of a promise.</em></p>
<p>It's important to note that a promise is said to be settled when it is resolved or rejected.</p>
<p>Now that you know how promises are created, let's look at how you may consume them.</p>
<h3 id="heading-how-to-consume-a-promise">How to Consume a Promise</h3>
<p>Consuming a promise involves the following steps:</p>
<ol>
<li><strong>Obtain a reference to the promise:</strong> To consume a promise, you first need to obtain a reference to it. Based on the code from the previous section, our reference to a promise will be the <code>myPromise</code> object.</li>
<li><strong>Attach callbacks to the promise:</strong> Once you have a reference, you can attach callback functions by using the <code>.then</code> and <code>.catch</code> methods. The <code>.then</code> method is called when a promise is fulfilled and the <code>.catch</code> method is called when a promise is rejected.</li>
<li><strong>Wait for the promise to be fulfilled or rejected:</strong> Once you've attached callbacks to the promise, you can wait for the promise to be fulfilled or rejected.</li>
</ol>
<p>Here is an example of how you might consume a promise:</p>
<pre><code class="lang-javascript">myPromise
    .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(result);
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(error);
    });
</code></pre>
<p>Once the promise is fulfilled, the <code>.then</code> callback method will be called with the resolved value. And if the promise is rejected, the <code>.catch</code> method will be called with an error message.</p>
<p>You can also add the <code>.finally()</code> method, which will be called after a promise is settled. This means that <code>.finally()</code> will be invoked regardless of the status of a promise (whether resolved or rejected).</p>
<pre><code class="lang-javascript">myPromise
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(error);
  })
  .finally(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">//code here will be executed regardless of the status</span>
    <span class="hljs-comment">//of a promise (fulfilled or rejected)</span>
  });
</code></pre>
<h3 id="heading-how-to-chain-promises">How to Chain Promises</h3>
<p>Promise chaining is a pattern that allows for a clear and easy-to-understand approach to handling asynchronous operations.</p>
<p>The pattern involves connecting multiple promises in a sequence, where the output of one promise is passed as input to the next promise.</p>
<p>The linking of the promises is achieved using the <code>then()</code> method. This method uses a callback function as an argument and returns a new promise. The new promise is then resolved with the value returned by the callback function.</p>
<p>Here is an example of promise chaining:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://example.com/data'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> processData(data))
    .then(<span class="hljs-function"><span class="hljs-params">processedData</span> =&gt;</span> {
        <span class="hljs-comment">// do something with the processed data</span>
    })
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error))
</code></pre>
<p>From the above code:</p>
<ul>
<li>The first promise, which is the <code>fetch API</code> function, is fetching data from a server. </li>
<li>The second promise is parsing the response as JSON. </li>
<li>The third promise is processing the data. </li>
<li>The fourth promise is performing action on the data.</li>
<li>The <code>.catch</code> method at the end of the chain will handle any errors that occurred in any of the previous promises.</li>
</ul>
<p>It's important to keep in mind that <code>.then</code> methods are executed asynchronously and in order, each one waiting for the previous one to be resolved, and that the returned value of each <code>.then</code> will be passed as an argument to the next one.</p>
<h3 id="heading-error-handling">Error Handling</h3>
<p>When a promise is rejected, it will trigger the <code>.catch()</code> method, which handles errors. The <code>.catch()</code> method takes a single argument, which is the error thrown.</p>
<p>Another way of handling errors in a promise is by using the "try-catch" block inside a <code>.then</code> method.</p>
<p>Here is an example:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"https://api.github.com/users/octocat"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">//processing received data</span>
      <span class="hljs-built_in">console</span>.log(data);
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.log(error);
    }
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>From the above code:</p>
<ul>
<li>The <code>fetch()</code> function makes a request to the GitHub API to fetch user data.</li>
<li>The "try-catch" block is used inside the second <code>.then</code> method to handle any error that may occur when processing the data received from the server. </li>
<li>And the outer <code>.catch</code> method will only catch errors that occur during the fetch request.</li>
</ul>
<p>Handling errors is very important because promises are used to handle asynchronous operations, and these operations may fail for various reasons.</p>
<p>If an error occurs during the execution of a promise and it is not handled, the program will continue to execute and may lead to unexpected behaviour or crashes.</p>
<p>By handling errors, we can ensure that the program can continue to function even when an error occurs and also provide meaningful feedback to the user about the problem.</p>
<h3 id="heading-how-to-use-the-promiseall-method">How to Use the Promise.all Method</h3>
<p>The <code>Promise.all()</code> method takes an array of promises as input and returns a single promise that is fulfilled when all input promises have been fulfilled. It can be useful when you wait for multiple promises to be resolved before taking action.</p>
<p>For example, if you want to fetch data from multiple URLs.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> promise1 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/1'</span>);
<span class="hljs-keyword">let</span> promise2 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/2'</span>);
<span class="hljs-keyword">let</span> promise3 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/3'</span>);
</code></pre>
<p>Here, <code>promise1</code>, <code>promise2</code>, and <code>promise3</code> are promises that are fetching data from three different URLs.</p>
<p>Now, you can use <code>Promise.all([promise1, promise2, promise3])</code> to wait for all the promises to resolve before doing something with the data, as shown below.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.all([promise1, promise2, promise3])
.then(<span class="hljs-function">(<span class="hljs-params">values</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(values);
})
</code></pre>
<p>In the above example:</p>
<ul>
<li><code>Promise.all()</code> takes an array of promises as input and returns a new promise. </li>
<li>The <code>then</code> method is then called on the returned promise to log the resolved values of all the input promises in the order they were passed to <code>Promise.all()</code>.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-26-103003-1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Note that in an instance where any input promises are rejected, the returned promise will also be rejected with the value of the first rejected promise. </p>
<h3 id="heading-how-to-use-the-fetch-api-with-promises">How to Use the Fetch API with Promises</h3>
<p>I have been using the Fetch API for some examples in this article, and I understand that it may be unfamiliar to some readers. So I created this section to explain the basics of the Fetch API for those who may need to become more familiar with it.</p>
<p>The Fetch API is a built-in JavaScript feature that allows you to make network requests, such as fetching data from a server. It is a modern alternative to the older XMLHttpRequest API and is designed to be easier and more powerful.</p>
<p>Here is an example of how to use the Fetch API to fetch data from a server:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://some-api.com/data'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
  });
</code></pre>
<p>In this example,</p>
<ul>
<li>The <code>fetch()</code> method is used to make a request to the server located at "<a target="_blank" href="https://some-api.com/data">https://some-api.com/data</a>". The returned value is a promise that will be fulfilled with the server's response.</li>
<li>The first <code>.then()</code> method is called to consume the promise and extract JSON data from the response.  </li>
<li>The next <code>then()</code> method is called to log the extracted data to the console.</li>
<li>If any errors occur, they will be caught in the <code>catch()</code> method and logged to the console.</li>
</ul>
<p>I hope the above explanation helps to clear up any confusion about the Fetch API and allows you to better understand the examples provided in this article.</p>
<h2 id="heading-async-functions-with-asyncawait"><strong>Async Functions with <code>async</code>/<code>await</code></strong></h2>
<p><code>Async/Await</code> is a feature that allows you to write asynchronous code in a more synchronous, readable way. </p>
<ul>
<li><code>async</code> is a keyword that is used to declare a function as asynchronous. </li>
<li><code>await</code> is a keyword that is used inside an <code>async</code> function to pause the execution of the function until a promise is resolved. </li>
</ul>
<p>Here's an example of how you can use <code>async/await</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/1'</span>);
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
  <span class="hljs-built_in">console</span>.log(data);
}

getData();
</code></pre>
<p>In this example, </p>
<ul>
<li>the <code>getData</code> function is declared as an asynchronous function using the <code>async</code> keyword. </li>
<li>Inside the asynchronous function, we use the <code>await</code> keyword to wait for the <code>fetch</code> function to complete and retrieve some data from an API. </li>
<li>Once the data is retrieved, we use <code>await</code> again to wait and parse the retrieved data as JSON.</li>
<li>And then finally, we log the data to the console.</li>
</ul>
<p>"Aync/Await" is a powerful tool for handling asynchronous operations. It allows for more readable and maintainable code by eliminating the need for callbacks and providing a more intuitive way to handle asynchronous operations.</p>
<p>Using the "async" keyword before a function definition and the "await" keyword before an asynchronous operation makes the code look more like synchronous code, making it easier to understand.</p>
<p>Overall, "Async/Await" is valuable to the JavaScript developer's toolbox and can significantly simplify handling asynchronous operations in your code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In summary, asynchronous programming is an essential concept in JavaScript that allows your code to run in the background without blocking the execution of other code. </p>
<p>Developers can create more efficient and responsive applications by using features like callbacks, async/await, and promises.</p>
<p>Asynchronous programming can be tricky to understand at first. But with practice and a solid understanding of the concepts, it becomes a powerful tool for building high-performance web applications.</p>
<p>Thank you for reading this article!</p>
<p>If you enjoyed this article and want to learn more about programming, follow me on Instagram at <a target="_blank" href="https://www.instagram.com/alege_dev/">@alege_dev</a>, where I post regular updates and tips on various programming topics. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Simplify Asynchronous JavaScript using the Result-Error Pattern ]]>
                </title>
                <description>
                    <![CDATA[ By Ken Snyder Over the last 18 years of programming, I've had to deal with asynchronous behavior in virtually every project.  Since the adoption of async-await in JavaScript, we've learned that async-await makes a lot of code more pleasant and easier... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/simplify-asynchronous-javascript-using-the-result-error-pattern/</link>
                <guid isPermaLink="false">66d45f65ffe6b1f641b5f9f7</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 18 Jan 2022 22:08:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/locomotive-gfe169d971_1920-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ken Snyder</p>
<p>Over the last 18 years of programming, I've had to deal with asynchronous behavior in virtually every project. </p>
<p>Since the adoption of async-await in JavaScript, we've learned that async-await makes a lot of code more pleasant and easier to reason about.</p>
<p>Recently I noticed that when I work with a resource that needs to asynchronously connect and disconnect, I end up writing code like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// NOT MY FAVORITE PATTERN</span>
router.get(<span class="hljs-string">'/users/:id'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> Client();
  <span class="hljs-keyword">let</span> user;
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> client.connect();
    user = <span class="hljs-keyword">await</span> client.find(<span class="hljs-string">'users'</span>).where(<span class="hljs-string">'id'</span>, req.path.id);
  } <span class="hljs-keyword">catch</span>(error) {
    res.status(<span class="hljs-number">500</span>);
    user = { error };
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-keyword">await</span> client.close();
  }
  res.json(user);
});
</code></pre>
<p>It gets verbose because we have to use try/catch to handle errors.</p>
<p>Examples of such resources include databases, ElasticSearch, command lines, and ssh.</p>
<p>In those use cases, I've settled into a code pattern I'm calling the Result-Error Pattern.</p>
<p>Consider rewriting the code above like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// I LIKE THIS PATTERN BETTER</span>
router.get(<span class="hljs-string">'/users/:id'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> { <span class="hljs-attr">result</span>: user, error } = <span class="hljs-keyword">await</span> withDbClient(<span class="hljs-function"><span class="hljs-params">client</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> client.find(<span class="hljs-string">'users'</span>).where(<span class="hljs-string">'id'</span>, req.path.id);
  });
  <span class="hljs-keyword">if</span> (error) {
    res.status(<span class="hljs-number">500</span>);
  }
  res.json({ user, error });
});
</code></pre>
<p>Notice a few things:</p>
<ol>
<li>The database client gets created for us and our callback can just utilize it.</li>
<li>Instead of capturing errors in a try-catch block, we rely on <code>withDbClient</code> to return errors.</li>
<li>The result is always called <code>result</code> because our callback may return any kind of data.</li>
<li>We don't have to close the resource.</li>
</ol>
<p>So what does <code>withDbClient</code> do?</p>
<ol>
<li>It handles creating the resource, connecting and closing.</li>
<li>It handles try, catch, and finally.</li>
<li>It ensures that there will be no uncaught exceptions thrown from <code>withDbClient</code>.</li>
<li>It ensures that any exceptions thrown in the handler also get caught inside <code>withDbClient</code>.</li>
<li>It ensures that <code>{ result, error }</code> will always be returned.</li>
</ol>
<p>Here is an example implementation:</p>
<pre><code class="lang-js"><span class="hljs-comment">// EXAMPLE IMPLEMENTATION</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withDbClient</span>(<span class="hljs-params">handler</span>) </span>{
  <span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> DbClient();
  <span class="hljs-keyword">let</span> result = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">let</span> error = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> client.connect();
    result = <span class="hljs-keyword">await</span> handler(client);
  } <span class="hljs-keyword">catch</span> (e) {
    error = e;
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-keyword">await</span> client.close();
  }
  <span class="hljs-keyword">return</span> { result, error };
}
</code></pre>
<h2 id="heading-a-step-further">A step further</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/pexels-tom-fisk-1595104.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Photo by <a target="_blank" href="https://www.pexels.com/@tomfisk">Tom Fisk</a> from Pexels</em></p>
<p>What about a resource that does not need to be closed? Well the Result-Error Pattern can still be nice!</p>
<p>Consider the following use of <code>fetch</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// THIS IS NICE AND SHORT</span>
<span class="hljs-keyword">const</span> { data, error, response } = <span class="hljs-keyword">await</span> fetchJson(<span class="hljs-string">'/users/123'</span>);
</code></pre>
<p>Its implementation might be the following:</p>
<pre><code class="lang-js"><span class="hljs-comment">// EXAMPLE IMPLEMENTATION</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchJson</span>(<span class="hljs-params">...args</span>) </span>{
  <span class="hljs-keyword">let</span> data = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">let</span> error = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">let</span> response = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(...args);
    <span class="hljs-keyword">if</span> (response.ok) {
      <span class="hljs-keyword">try</span> {
        data = <span class="hljs-keyword">await</span> response.json();
      } <span class="hljs-keyword">catch</span> (e) {
        <span class="hljs-comment">// not json</span>
      }
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// note that statusText is always "" in HTTP2</span>
      error = <span class="hljs-string">`<span class="hljs-subst">${response.status}</span> <span class="hljs-subst">${response.statusText}</span>`</span>;
    }
  } <span class="hljs-keyword">catch</span>(e) {
    error = e;  
  }
  <span class="hljs-keyword">return</span> { data, error, response };
}
</code></pre>
<h2 id="heading-higher-level-use">Higher-level use</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/aerial-g3ccde9887_1920.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Photo by <a target="_blank" href="https://pixabay.com/users/16018388-16018388/">16018388</a> from Pixabay</em></p>
<p>We don't have to stop at low-level use. What about other functions that may end with a result or error?</p>
<p>Recently, I wrote an app with a lot of ElasticSearch interactions. I decided to also use the Result-Error pattern on higher-level functions.</p>
<p>For instance, searching for posts produces an array of ElasticSearch documents and returns result and error like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { result, error, details } = <span class="hljs-keyword">await</span> findPosts(query);
</code></pre>
<p>If you've worked with ElasticSearch, you'll know that responses are verbose and data is nested several layers inside the response. Here, <code>result</code> is an object containing:</p>
<ol>
<li><code>records</code> – An Array of documents</li>
<li><code>total</code> – The total number of documents if a limit was not applied</li>
<li><code>aggregations</code> – ElasticSearch faceted-search information</li>
</ol>
<p>As you might guess, <code>error</code> may be an error message and <code>details</code> is the full ElasticSearch response in case you need things like error metadata, highlights, or query time.</p>
<p>My implementation for searching ElasticSearch with a query object reads something like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Fetch from the given index name with the given query</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">query</span>(<span class="hljs-params">index, query</span>) </span>{
  <span class="hljs-comment">// Our Result-Error Pattern at the low level  </span>
  <span class="hljs-keyword">const</span> { result, error } = <span class="hljs-keyword">await</span> withEsClient(<span class="hljs-function"><span class="hljs-params">client</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> client.search({
      index,
      <span class="hljs-attr">body</span>: query.getQuery(),
    });
  });
  <span class="hljs-comment">// Returning a similar object also with result-error</span>
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">result</span>: formatRecords(result),
    error,
    <span class="hljs-attr">details</span>: result || error?.meta,
  };
}

<span class="hljs-comment">// Extract records from responses </span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatRecords</span>(<span class="hljs-params">result</span>) </span>{
  <span class="hljs-comment">// Notice how deep ElasticSearch buries results?</span>
  <span class="hljs-keyword">if</span> (result?.body?.hits?.hits) {
    <span class="hljs-keyword">const</span> records = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> hit <span class="hljs-keyword">of</span> result.body.hits.hits) {
      records.push(hit._source);
    }
    <span class="hljs-keyword">return</span> {
      records,
      <span class="hljs-attr">total</span>: result.body.hits.total?.value || <span class="hljs-number">0</span>,
      <span class="hljs-attr">aggregations</span>: result.aggregations,
    };
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">records</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-literal">null</span>, <span class="hljs-attr">aggregations</span>: <span class="hljs-literal">null</span> };
  }
}
</code></pre>
<p>And then the <code>findPosts</code> function becomes something simple like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findPosts</span>(<span class="hljs-params">query</span>) </span>{
  <span class="hljs-keyword">return</span> query(<span class="hljs-string">'posts'</span>, query);
}
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>Here are the key aspects of a function that implements the Result-Error Pattern:</p>
<ol>
<li>Never throw exceptions.</li>
<li>Always return an object with the results and the error, where one may be null.</li>
<li>Hide away any asynchronous resource creation or cleanup.</li>
</ol>
<p>And here are the corresponding benefits of calling functions that implement the Result-Error Pattern:</p>
<ol>
<li>You don't need to use try-catch blocks.</li>
<li>Handling error cases is as simple as <code>if (error)</code>.</li>
<li>You don't need to worry about setup or cleanup operations.</li>
</ol>
<p>Don't take my word for it, try it yourself!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code ]]>
                </title>
                <description>
                    <![CDATA[ NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications.  Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other requ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/nodejs-eventloop-tutorial/</link>
                <guid isPermaLink="false">66ba2a47c346e93df556afec</guid>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tejan Singh ]]>
                </dc:creator>
                <pubDate>Mon, 30 Aug 2021 15:11:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/oliver-hale-2cYueJxEDz8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications. </p>
<p>Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other request.</p>
<p>In this article, you will learn and understand how NodeJS works and handles all functions or requests sent to a server either <em>synchronously</em> or <em>asynchronously</em>. </p>
<h2 id="heading-what-is-an-event-loop">What is an Event Loop?</h2>
<p>You might have guessed it right – Node handles requests using an <strong>Event loop</strong> inside the NodeJS environment. But first, let's understand some basic terms which will help us understand the whole mechanism.</p>
<p>An event loop is an <strong>event-listener</strong> which functions inside the NodeJS environment and is always ready to listen, process, and output for an <em>event</em>.</p>
<p>An event can be anything from a mouse click to a keypress or a timeout.</p>
<h2 id="heading-what-are-synchronous-and-asynchronous-programming">What are Synchronous and Asynchronous programming?</h2>
<p><strong>Synchronous programming</strong> means that the code runs in the sequence it is defined. In a synchronous program, when a function is called and has returned some value, only then will the next line be executed.</p>
<p>Let's understand with this an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> listItems = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">items</span>) </span>{
  items.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>) </span>{
    <span class="hljs-built_in">console</span>.log(item)
  })
}

<span class="hljs-keyword">const</span> items = [<span class="hljs-string">"Buy milk"</span>, <span class="hljs-string">"Buy coffee"</span>]

listItems(items)
</code></pre>
<pre><code>The output will look like <span class="hljs-built_in">this</span>:

<span class="hljs-string">"Buy milk"</span>
<span class="hljs-string">"Buy coffee"</span>
</code></pre><p>In this example, when the <code>listItems(items)</code> function is called, it will loop through the array of items. The <code>console.log(item)</code> function gets called first for the first item of the array and it prints <code>"Buy milk"</code>. Then again <code>console.log(item)</code> gets executed and this time it passes the second item of the array and prints <code>"Buy coffee"</code>.</p>
<p>So you can say that the function was executed in the <strong>sequence</strong> it was defined.</p>
<p><strong>Asynchronous programming</strong>, on the other hand, refers code that doesn't execute in sequence. These functions are performed not according to the sequence they are defined inside a program but only when certain conditions are met. </p>
<p>For example, <code>setTimeOut()</code> performs a task after a delay of a certain predefined number of miliseconds.</p>
<pre><code class="lang-js">setTimeOut(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span>( <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>) )
}, <span class="hljs-number">3000</span>)
</code></pre>
<p>These functions do not run line by line but only when they are required to run, irrespective of the function's declaration. In this case, the function  runs automatically after 3 seconds when all synchronous functions have been executed.</p>
<p><em>Note: Asynchronous functions will run and execute only after all the synchronous functions have been executed. Until then, they will be processed in the background.</em></p>
<p>If you want to learn more about NodeJS and asynchronous programming, you can refer to this <a target="_blank" href="https://www.freecodecamp.org/news/node-js-what-when-where-why-how-ab8424886e2/">article</a></p>
<p>But, how does NodeJS handle asynchronous functions in the background and run all synchronous functions first? All these mechanisms can be easily explained with the NodeJS event loop.</p>
<h2 id="heading-how-does-an-event-loop-work">How Does an Event Loop Work?</h2>
<p>Now let's see how NodeJS event loops can execute a simple synchronous program using a Nodejs event loop diagram. Then we'll examine how Node executes the program line by line.</p>
<p>As we go through this section you'll start to understand what you are seeing here:
<img src="https://www.freecodecamp.org/news/content/images/2021/08/1.PNG" alt="1" width="600" height="400" loading="lazy"></p>
<p>In the top-left corner, you have a Node file that is going to get executed. At the bottom left, you have an output terminal for the program. Then you have <em>Call stack, Node APIs and Callback queue.</em> All these together constitute the NodeJS environment.</p>
<p>For synchronous programming, you only need to focus on the call stack. This is the only part of the NodeJS environment that will be working in this case.</p>
<p>A callback stack is a data structure that you use to keep track of the execution of all functions that will run inside the program. This data structure has only one open end to add or remove top items.</p>
<p>When the program starts executing, it first gets wrapped inside an anonymous <code>main()</code> function. This is automatically defined by NodeJS. So <code>main()</code> gets pushed first to the callback stack.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/2.PNG" alt="2" width="600" height="400" loading="lazy"></p>
<p>Next, the variables <code>a</code> and <code>b</code> are created and their sum is stored in a variable <code>sum</code>. All these values are stored in memory. </p>
<p>Now, the <code>console.log()</code> is a function that is called and pushed inside the callback stack. It gets executed and you can see the output on the terminal screen.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/3.PNG" alt="3" width="600" height="400" loading="lazy"></p>
<p>After this function gets executed, it is removed from the callback stack. Then the <code>main()</code> is also removed as nothing is left to be called from the program. This is how a synchronous program gets executed.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/4.PNG" alt="4" width="600" height="400" loading="lazy">
<img src="https://www.freecodecamp.org/news/content/images/2021/08/5.PNG" alt="5" width="600" height="400" loading="lazy"></p>
<p>Now, let's see how asynchronous functions or programs get executed inside NodeJS. We need the callback stack, Node APIs and callback queue all together to process an asynchronous function.</p>
<p>Let's start by looking at this example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/1-1.PNG" alt="1-1" width="600" height="400" loading="lazy"></p>
<p>As usual, when the program starts executing, first the <code>main()</code> function gets added to the callback stack. Then <code>console.log("Start")</code> is called and added to the callback stack. After processing, the output is visible on the terminal and then it gets removed from the callback stack. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/2-1.PNG" alt="2-1" width="600" height="400" loading="lazy">
<img src="https://www.freecodecamp.org/news/content/images/2021/08/3-1.PNG" alt="3-1" width="600" height="400" loading="lazy"></p>
<p>Now the next is the <code>setTimeOut(...Zero...)</code> function which gets added to the callback stack. </p>
<p>As this is an asynchronous function, it will <strong>not</strong> get processed in the callback stack. It is then added from the callback stack to the Node APIs where an event is registered and a callback function is set to get processed in the background. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/4-1.PNG" alt="4-1" width="600" height="400" loading="lazy">
<img src="https://www.freecodecamp.org/news/content/images/2021/08/5-1.PNG" alt="5-1" width="600" height="400" loading="lazy"></p>
<p>Next is the <code>setTimeOut(...Two..)</code> which also gets added to the Node API from the callback stack as it is an asynchronous function. Then another callback function gets set to be processed after a 2 second timeout in the background. Up until this point other functions can be performed. </p>
<p>This is called <strong>non-blocking</strong> behaviour where all the synchronous functions are processed and executed first and asynchronous functions are processed in the background while waiting their turn to get executed.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/6.PNG" alt="6" width="600" height="400" loading="lazy">
<img src="https://www.freecodecamp.org/news/content/images/2021/08/7.PNG" alt="7" width="600" height="400" loading="lazy"></p>
<p>Next, the <code>console.log("End")</code> function is called at last in the callback stack and gets processed here. You can see the output on the terminal. Now, all the synchronous functions are processed, and <code>main()</code> is removed from the callback stack.</p>
<p>In the background, all the asynchronous functions get processed and their callbacks are stored in the callback queue. The one which is processed first will be added first in the queue for execution in the callback stack.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/8.PNG" alt="8" width="600" height="400" loading="lazy">
<img src="https://www.freecodecamp.org/news/content/images/2021/08/9.PNG" alt="9" width="600" height="400" loading="lazy">
<img src="https://www.freecodecamp.org/news/content/images/2021/08/10.PNG" alt="10" width="600" height="400" loading="lazy"></p>
<p><em>Note: Asynchronous functions cannot run inside a callback stack until it gets emptied. That means that after <code>main()</code> is removed from call stack, only then can all asynchronous functions start executing.</em></p>
<p>Now, one by one they are pushed to the callback stack using the <strong>event loop</strong> and finally get executed. Each of the callback functions will print the value with the <code>console.log()</code> function getting called each time.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/11.PNG" alt="11" width="600" height="400" loading="lazy"></p>
<p>At last, these are also removed after being executed and now the callback stack is empty.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/12.PNG" alt="12" width="600" height="400" loading="lazy"></p>
<p>This is how NodeJS will execute synchronous and asynchronous funtions inside the environment and how the event loop manages to call asynchronous functions.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned the internal working of NodeJS and saw how asynchronous programs get executed. </p>
<p>Now you should understand why the two second time delay function does not block the rest of the program from executing. You also know why the zero second delay function prints the value at last after "End" prints.</p>
<p>That’s all! I hope you enjoyed reading this article and learned something new. Do share this article if you find it useful.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Async/Await Tutorial – Learn Callbacks, Promises, and Async/Await in JS by Making Ice Cream 🍧🍨🍦 ]]>
                </title>
                <description>
                    <![CDATA[ Today we're going to build and run an ice cream shop and learn asynchronous JavaScript at the same time. Along the way, you'll learn how to use: Callbacks Promises Async / Await Here's what we'll cover in this article: What is Asynchronous JavaSc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-async-await-tutorial-learn-callbacks-promises-async-await-by-making-icecream/</link>
                <guid isPermaLink="false">66b2095aa5be9a107f4341cd</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joy Shaheb ]]>
                </dc:creator>
                <pubDate>Wed, 02 Jun 2021 14:45:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/FCC-Thumbnail--3-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Today we're going to build and run an <strong>ice cream shop</strong> and learn <strong>asynchronous JavaScript</strong> at the same time. Along the way, you'll learn how to use:</p>
<ul>
<li>Callbacks</li>
<li>Promises</li>
<li>Async / Await</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1j935dg72g9u8zvh2oi.png" alt="Alt Text" width="1107" height="576" loading="lazy"></p>
<h1 id="heading-heres-what-well-cover-in-this-article">Here's what we'll cover in this article:</h1>
<ul>
<li>What is Asynchronous JavaScript?</li>
<li>Synchronous vs Asynchronous JavaScript</li>
<li>How Callbacks Work in JavaScript</li>
<li>How Promises Work in JavaScript</li>
<li>How Async / Await Works in JavaScript</li>
</ul>
<p>So let's dive in!</p>
<h2 id="heading-you-can-watch-this-tutorial-on-youtube-as-well-if-you-like">You can watch this tutorial on YouTube as well if you like:</h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/n5ZtTO1ArWg" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h1 id="heading-what-is-asynchronous-javascript">What is Asynchronous JavaScript?</h1>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7yd96tgxvuowqmfgcx6b.png" alt="Alt Text" width="1498" height="703" loading="lazy"></p>
<p>If you want to build projects efficiently, then this concept is for you.</p>
<p>The theory of async JavaScript helps you break down big complex projects into smaller tasks.</p>
<p>Then you can use any of these three techniques – <strong>callbacks, promises or Async/await</strong> – to run those small tasks in a way that you get the best results.</p>
<p>Let's dive in!🎖️</p>
<h1 id="heading-synchronous-vs-asynchronous-javascript">Synchronous vs Asynchronous JavaScript</h1>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/arzbf1rc3pi4yi6u8wup.png" alt="Alt Text" width="1253" height="642" loading="lazy"></p>
<h2 id="heading-what-is-a-synchronous-system">What is a Synchronous System?</h2>
<p>In a synchronous system, tasks are completed one after another.</p>
<p>Think of this as if you have just one hand to accomplish 10 tasks. So, you have to complete one task at a time.</p>
<p>Take a look at the GIF 👇 – one thing is happening at a time here:</p>
<p><img src="https://media.giphy.com/media/ICIS16DkE9qB9HVxtq/giphy.gif" alt="Synchronous System" width="480" height="258" loading="lazy"></p>
<p>You'll see that until the first image is loaded completely, the second image doesn't start loading.</p>
<p>Well, JavaScript is by default Synchronous <strong>[single threaded]</strong>. Think about it like this – one thread means one hand with which to do stuff.</p>
<h2 id="heading-what-is-an-asynchronous-system">What is an Asynchronous System?</h2>
<p>In this system, tasks are completed independently.</p>
<p>Here, imagine that for 10 tasks, you have 10 hands. So, each hand can do each task independently and at the same time.</p>
<p>Take a look at the GIF 👇 – you can see that each image loads at the same time.</p>
<p><img src="https://media.giphy.com/media/MMDnmJnE7uhX6KtcKc/giphy.gif" alt="Asynchronous System" width="480" height="258" loading="lazy"></p>
<p>Again, all the images are loading at their own pace. None of them is waiting for any of the others.</p>
<h2 id="heading-to-summarize-synchronous-vs-asynchronous-js">To Summarize Synchronous vs Asynchronous JS:</h2>
<p>When three images are on a marathon, in a:</p>
<ul>
<li><strong>Synchronous</strong> system, three images are in the same lane. One can't overtake the other. The race is finished one by one. If image number 2 stops, the following image stops.</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w1r9y4ghhq0t8wjb1u9h.png" alt="Alt Text" width="1544" height="748" loading="lazy"></p>
<ul>
<li><strong>Asynchronous system,</strong> the three images are in different lanes. They'll finish the race on their own pace. Nobody stops for anybody:</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehknx5shc4orh32s0ktk.png" alt="Alt Text" width="1544" height="748" loading="lazy"></p>
<h2 id="heading-synchronous-and-asynchronous-code-examples">Synchronous and Asynchronous Code Examples</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pzbnpcza9rbj8xgiby95.png" alt="Alt Text" width="1156" height="511" loading="lazy"></p>
<p>Before starting our project, let's look at some examples and clear up any doubts.</p>
<h3 id="heading-synchronous-code-example">Synchronous Code Example</h3>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5m6p1qy522lj3auvl5ty.png" alt="Alt Text" width="1054" height="421" loading="lazy"></p>
<p>To test a synchronous system, write this code in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">" I "</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">" eat "</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">" Ice Cream "</span>);
</code></pre>
<p>Here's the result in the console: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54izy7zyo52j2z6netls.png" alt="Alt Text" width="919" height="358" loading="lazy"></p>
<h3 id="heading-asynchronous-code-example">Asynchronous code example</h3>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y5d0o8unbe8c67qeqz0w.png" alt="Alt Text" width="1054" height="421" loading="lazy"></p>
<p>Let's say it takes two seconds to eat some ice cream. Now, let's test out an asynchronous system. Write the below code in JavaScript.</p>
<p><strong>Note:</strong> Don't worry, we'll discuss the <code>setTimeout()</code> function later in this article.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I"</span>);

<span class="hljs-comment">// This will be shown after 2 seconds</span>

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"eat"</span>);
},<span class="hljs-number">2000</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Ice Cream"</span>)
</code></pre>
<p>And here's the result in the console: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o44c2t0r7bknkadoumgx.png" alt="Alt Text" width="924" height="364" loading="lazy"></p>
<p>Now that you know the difference between synchronous and async operations, let's build our ice cream shop.</p>
<h2 id="heading-how-to-setup-our-project">How to Setup our Project</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2mzbtcnm67v2iys7cix7.png" alt="Alt Text" width="1253" height="598" loading="lazy"></p>
<p>For this project you can just open <a target="_blank" href="https://codepen.io/">Codepen.io</a> and start coding. Or, you can do it in VS code or the editor of your choice.</p>
<p>Open the JavaScript section, and then open your developer console. We'll write our code and see the results in the console.</p>
<h1 id="heading-what-are-callbacks-in-javascript">What are Callbacks in JavaScript?</h1>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5iloofqsv3lcdl4flsi.png" alt="Alt Text" width="1253" height="598" loading="lazy"></p>
<p>When you nest a function inside another function as an argument, that's called a callback.</p>
<p>Here's an illustration of a callback:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uz3pl56lmoc2pq7wzi2s.png" alt="Image" width="1054" height="543" loading="lazy">
<em><strong>An example of a callback</strong></em></p>
<p>Don't worry, we'll see some examples of callbacks in a minute.</p>
<h3 id="heading-why-do-we-use-callbacks">Why do we use callbacks?</h3>
<p>When doing a complex task, we break that task down into smaller steps. To help us establish a relationship between these steps according to time (optional) and order, we use callbacks.</p>
<p>Take a look at this example:👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o05q7ortgctx2oeyntfn.png" alt="Alt Text" width="2338" height="1374" loading="lazy">
<em><strong>Chart contains steps to make ice cream</strong></em></p>
<p>These are the small steps you need to take to make ice cream. Also note that in this example, the order of the steps and timing are crucial. You can't just chop the fruit and serve ice cream.</p>
<p>At the same time, if a previous step is not completed, we can't move on to the next step.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2v1rn50smjul9arkneza.png" alt="Alt Text" width="2338" height="1316" loading="lazy"></p>
<p>To explain that in more detail, let's start our ice cream shop business.</p>
<h2 id="heading-but-wait">But Wait...</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cq8exwor5aiciu2j6jwu.png" alt="Alt Text" width="1488" height="600" loading="lazy"></p>
<p>The shop will have two parts:</p>
<ul>
<li>The storeroom will have all the ingredients [Our Backend]</li>
<li>We'll produce ice cream in our kitchen [The frontend]</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i69bws707m5rvsj34i9o.png" alt="Alt Text" width="1994" height="608" loading="lazy"></p>
<h2 id="heading-lets-store-our-data">Let's store our data</h2>
<p>Now, we're gonna store our ingredients inside an object. Let's start!</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihezrht8dgg9xn8lm2k9.png" alt="Alt Text" width="906" height="427" loading="lazy"></p>
<p>You can store the ingredients inside objects like this: 👇</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> stocks = {
    <span class="hljs-attr">Fruits</span> : [<span class="hljs-string">"strawberry"</span>, <span class="hljs-string">"grapes"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"apple"</span>]
 }
</code></pre>
<p>Our other ingredients are here: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6dcwr770l0ubupv0r2gj.png" alt="Alt Text" width="1106" height="642" loading="lazy"></p>
<p>You can store these other ingredients in JavaScript objects like this: 👇</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> stocks = {
    <span class="hljs-attr">Fruits</span> : [<span class="hljs-string">"strawberry"</span>, <span class="hljs-string">"grapes"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"apple"</span>],
    <span class="hljs-attr">liquid</span> : [<span class="hljs-string">"water"</span>, <span class="hljs-string">"ice"</span>],
    <span class="hljs-attr">holder</span> : [<span class="hljs-string">"cone"</span>, <span class="hljs-string">"cup"</span>, <span class="hljs-string">"stick"</span>],
    <span class="hljs-attr">toppings</span> : [<span class="hljs-string">"chocolate"</span>, <span class="hljs-string">"peanuts"</span>],
 };
</code></pre>
<p>The entire business depends on what a customer <strong>orders</strong>. Once we have an order, we start production and then we serve ice cream. So, we'll create two functions -&gt;</p>
<ul>
<li><code>order</code></li>
<li><code>production</code></li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3bnzniiyamo0b9l7e806.png" alt="Alt Text" width="1253" height="598" loading="lazy"></p>
<p>This is how it all works: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8h8ra9wor8cs3dgddpb.png" alt="Alt Text" width="1138" height="663" loading="lazy">
<em>Get order from customer, fetch ingredients, start production, then serve.</em></p>
<p>Let's make our functions. We'll use arrow functions here:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> order = <span class="hljs-function">() =&gt;</span>{};

<span class="hljs-keyword">let</span> production = <span class="hljs-function">() =&gt;</span>{};
</code></pre>
<p>Now, let's establish a relationship between these two functions using a callback, like this: 👇</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> order = <span class="hljs-function">(<span class="hljs-params">call_production</span>) =&gt;</span>{

  call_production();
};

<span class="hljs-keyword">let</span> production = <span class="hljs-function">() =&gt;</span>{};
</code></pre>
<h3 id="heading-lets-do-a-small-test">Let's do a small test</h3>
<p>We'll use the <code>console.log()</code> function to conduct tests to clear up any doubts we might have regarding how we established the relationship between the two functions.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> order = <span class="hljs-function">(<span class="hljs-params">call_production</span>) =&gt;</span>{

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Order placed. Please call production"</span>)

<span class="hljs-comment">// function 👇 is being called </span>
  call_production();
};

<span class="hljs-keyword">let</span> production = <span class="hljs-function">() =&gt;</span>{

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Production has started"</span>)

};
</code></pre>
<p>To run the test, we'll call the <strong><code>order</code></strong> function. And we'll add the second function named <code>production</code> as its argument.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// name 👇 of our second function</span>
order(production);
</code></pre>
<p>Here's the result in our console 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u41ugdxxed1q8coz5hol.png" alt="Alt Text" width="918" height="325" loading="lazy"></p>
<h2 id="heading-take-a-break">Take a break</h2>
<p>So far so good – take a break!</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tnr74waq6noc0djln3qx.png" alt="Alt Text" width="1555" height="618" loading="lazy"></p>
<h2 id="heading-clear-out-the-consolelog">Clear out the console.log</h2>
<p>Keep this code and remove everything [don't delete our stocks variable]. On our first function, pass another argument so that we can receive the order [Fruit name]:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Function 1</span>

<span class="hljs-keyword">let</span> order = <span class="hljs-function">(<span class="hljs-params">fruit_name, call_production</span>) =&gt;</span>{

  call_production();
};

<span class="hljs-comment">// Function 2</span>

<span class="hljs-keyword">let</span> production = <span class="hljs-function">() =&gt;</span>{};


<span class="hljs-comment">// Trigger 👇</span>

order(<span class="hljs-string">""</span>, production);
</code></pre>
<p>Here are our steps, and the time each step will take to execute.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rphpp2lqjnk7f0tv5g3d.png" alt="Alt Text" width="2353" height="1374" loading="lazy">
<em><strong>Chart contains steps to make ice cream</strong></em></p>
<p>In this chart, you can see that step 1 is to place the order, which takes 2 seconds. Then step 2 is cut the fruit (2 seconds), step 3 is add water and ice (1 second), step 4 is to start the machine (1 second), step 5 is to select the container (2 seconds), step 6 is to select the toppings (3 seconds) and step 7, the final step, is to serve the ice cream which takes 2 seconds.</p>
<p>To establish the timing, the function <code>setTimeout()</code> is excellent as it is also uses a callback by taking a function as an argument.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qwrg1taugyhvjnkx8xpp.png" alt="Alt Text" width="1054" height="543" loading="lazy">
<em><strong>Syntax of a setTimeout() function</strong></em></p>
<p>Now, let's select our fruit and use this function:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// 1st Function</span>

<span class="hljs-keyword">let</span> order = <span class="hljs-function">(<span class="hljs-params">fruit_name, call_production</span>) =&gt;</span>{

  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.Fruits[fruit_name]}</span> was selected`</span>)

<span class="hljs-comment">// Order placed. Call production to start</span>
   call_production();
  },<span class="hljs-number">2000</span>)
};

<span class="hljs-comment">// 2nd Function</span>

<span class="hljs-keyword">let</span> production = <span class="hljs-function">() =&gt;</span>{
  <span class="hljs-comment">// blank for now</span>
};

<span class="hljs-comment">// Trigger 👇</span>
order(<span class="hljs-number">0</span>, production);
</code></pre>
<p>And here's the result in the console: 👇</p>
<p><strong>Note</strong> that the result is displayed after 2 seconds.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/edwji5vauypoezj3bxdk.png" alt="Alt Text" width="892" height="244" loading="lazy"></p>
<p>If you're wondering how we picked strawberry from our stock variable, here's the code with the format 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ia38z3x6b96xpq3aid91.png" alt="Alt Text" width="1498" height="424" loading="lazy"></p>
<p>Don't delete anything. Now we'll start writing our production function with the following code.👇 We'll use arrow functions:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> production = <span class="hljs-function">() =&gt;</span>{

  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"production has started"</span>)
  },<span class="hljs-number">0000</span>)

};
</code></pre>
<p>And here's the result 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5yskzvg7rezo2sg4lklq.png" alt="Alt Text" width="889" height="288" loading="lazy"></p>
<p>We'll nest another <code>setTimeout</code> function in our existing <code>setTimeout</code> function to chop the fruit. Like this: 👇</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> production = <span class="hljs-function">() =&gt;</span>{

  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"production has started"</span>)


    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The fruit has been chopped"</span>)
    },<span class="hljs-number">2000</span>)


  },<span class="hljs-number">0000</span>)
};
</code></pre>
<p>And here's the result 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4659l1mua0rv40rwyem7.png" alt="Alt Text" width="874" height="357" loading="lazy"></p>
<p>If you remember, here are our steps:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rphpp2lqjnk7f0tv5g3d.png" alt="Alt Text" width="2353" height="1374" loading="lazy">
<em><strong>Chart contains steps to make ice cream</strong></em></p>
<p>Let's complete our ice cream production by nesting a function inside another function – this is also known as a callback, remember?</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> production = <span class="hljs-function">() =&gt;</span>{

  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"production has started"</span>)
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The fruit has been chopped"</span>)
      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.liquid[<span class="hljs-number">0</span>]}</span> and <span class="hljs-subst">${stocks.liquid[<span class="hljs-number">1</span>]}</span> Added`</span>)
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
          <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"start the machine"</span>)
          <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Ice cream placed on <span class="hljs-subst">${stocks.holder[<span class="hljs-number">1</span>]}</span>`</span>)
            <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
              <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.toppings[<span class="hljs-number">0</span>]}</span> as toppings`</span>)
              <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"serve Ice cream"</span>)
              },<span class="hljs-number">2000</span>)
            },<span class="hljs-number">3000</span>)
          },<span class="hljs-number">2000</span>)
        },<span class="hljs-number">1000</span>)
      },<span class="hljs-number">1000</span>)
    },<span class="hljs-number">2000</span>)
  },<span class="hljs-number">0000</span>)

};
</code></pre>
<p>And here's the result in the console 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mq9bg6fqrc8apj7nu7b.png" alt="Alt Text" width="1285" height="705" loading="lazy"></p>
<p>Feeling confused?</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/man5l5pwavp9prio1wc0.png" alt="Alt Text" width="1291" height="613" loading="lazy"></p>
<p>This is called callback hell. It looks something like this (remember that code just above?): 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5rk7f8d920jzn22smjh.png" alt="Alt Text" width="1291" height="730" loading="lazy">
<em><strong>Illustration of Callback hell</strong></em></p>
<p>What's the solution to this?</p>
<h1 id="heading-how-to-use-promises-to-escape-callback-hell">How to Use Promises to Escape Callback Hell</h1>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3neys1hxsrifgg5qm6x.png" alt="Alt Text" width="1291" height="613" loading="lazy"></p>
<p>Promises were invented to solve the problem of callback hell and to better handle our tasks.</p>
<h2 id="heading-take-a-break-1">Take a break</h2>
<p>But first, take a break!</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bwfvel7kvm422gqvj0os.png" alt="Alt Text" width="1054" height="421" loading="lazy"></p>
<p>This is how a promise looks:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7qo1zheuin2825osozvc.png" alt="Alt Text" width="1291" height="644" loading="lazy">
<em><strong>illustration of a promise format</strong></em></p>
<p>Let's dissect promises together.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gozy5r1nfubzeq5t5t25.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezi9ogz0ergprgkmu68a.png" alt="Alt Text" width="1006" height="454" loading="lazy">
<em><strong>An illustration of the life of a promise</strong></em></p>
<p>As the above charts show, a promise has three states:</p>
<ul>
<li><strong>Pending:</strong> This is the initial stage. Nothing happens here. Think of it like this, your customer is taking their time giving you an order. But they haven't ordered anything yet.</li>
<li><strong>Resolved:</strong> This means that your customer has received their food and is happy.</li>
<li><strong>Rejected:</strong> This means that your customer didn't receive their order and left the restaurant.</li>
</ul>
<p>Let's adopt promises to our ice cream production case study.</p>
<h2 id="heading-but-wait-1">But wait...</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/634b6oyglkyoccsvr8l7.png" alt="Alt Text" width="1119" height="571" loading="lazy"></p>
<p>We need to understand four more things first -&gt;</p>
<ul>
<li>Relationship between time and work</li>
<li>Promise chaining</li>
<li>Error handling</li>
<li>The <code>.finally</code> handler</li>
</ul>
<p>Let's start our ice cream shop and understand each of these concepts one by one by taking baby steps.</p>
<h2 id="heading-relationship-between-time-and-work">Relationship between time and work</h2>
<p>If you remember, these are our steps and the time each takes to make ice cream"</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rphpp2lqjnk7f0tv5g3d.png" alt="Alt Text" width="2353" height="1374" loading="lazy">
<em><strong>Chart contains steps to make ice cream</strong></em></p>
<p>For this to happen, let's create a variable in JavaScript: 👇</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> is_shop_open = <span class="hljs-literal">true</span>;
</code></pre>
<p>Now create a function named <code>order</code> and pass two arguments named <code>time, work</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> order = <span class="hljs-function">(<span class="hljs-params"> time, work </span>) =&gt;</span>{

  }
</code></pre>
<p>Now, we're gonna make a promise to our customer, "We will serve you ice-cream" Like this -&gt;</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> order = <span class="hljs-function">(<span class="hljs-params"> time, work </span>) =&gt;</span>{

  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>( <span class="hljs-function">(<span class="hljs-params"> resolve, reject </span>)=&gt;</span>{ } )

  }
</code></pre>
<p>Our promise has 2 parts:</p>
<ul>
<li>Resolved [ ice cream delivered ]</li>
<li>Rejected [ customer didn't get ice cream ]</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> order = <span class="hljs-function">(<span class="hljs-params"> time, work </span>) =&gt;</span> {

  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>( <span class="hljs-function">(<span class="hljs-params"> resolve, reject </span>)=&gt;</span>{

    <span class="hljs-keyword">if</span>( is_shop_open ){

      resolve( )

    }

    <span class="hljs-keyword">else</span>{

      reject( <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Our shop is closed"</span>) )

    }

  })
}
</code></pre>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3wik2xel68yue93yapm6.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>Let's add the time and work factors inside our promise using a <code>setTimeout()</code> function inside our <code>if</code> statement. Follow me 👇</p>
<p><strong>Note:</strong> In real life, you can avoid the time factor as well. This is completely dependent on the nature of your work.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> order = <span class="hljs-function">(<span class="hljs-params"> time, work </span>) =&gt;</span> {

  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>( <span class="hljs-function">(<span class="hljs-params"> resolve, reject </span>)=&gt;</span>{

    <span class="hljs-keyword">if</span>( is_shop_open ){

      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{

       <span class="hljs-comment">// work is 👇 getting done here</span>
        resolve( work() )

<span class="hljs-comment">// Setting 👇 time here for 1 work</span>
       }, time)

    }

    <span class="hljs-keyword">else</span>{
      reject( <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Our shop is closed"</span>) )
    }

  })
}
</code></pre>
<p>Now, we're gonna use our newly created function to start ice-cream production.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Set 👇 time here</span>
order( <span class="hljs-number">2000</span>, <span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.Fruits[<span class="hljs-number">0</span>]}</span> was selected`</span>))
<span class="hljs-comment">//    pass a ☝️ function here to start working</span>
</code></pre>
<p>The result 👇 after 2 seconds looks like this:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/erzjup8wt505j502e73n.png" alt="Alt Text" width="757" height="169" loading="lazy"></p>
<p>Good job!</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8taajvjy6pfq35hu90nq.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<h2 id="heading-promise-chaining">Promise chaining</h2>
<p>In this method, we defining what we need to do when the first task is complete using the <code>.then</code> handler.  It looks something like this 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l27ytifkoedl22kc97lh.png" alt="Alt Text" width="1006" height="454" loading="lazy">
<em><strong>Illustration of promise chaining using .then handler</strong></em></p>
<p>The .then handler returns a promise when our original promise is resolved.</p>
<h4 id="heading-heres-an-example">Here's an Example:</h4>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1qpeewo19qbhzj47goos.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>Let me make it simpler: it's similar to giving instructions to someone. You tell someone to " First do this, then do that, then this other thing, then.., then.., then..." and so on.</p>
<ul>
<li>The first task is our original promise.</li>
<li>The rest of the tasks return our promise once one small bit of work is completed</li>
</ul>
<p>Let's implement this on our project. At the bottom of your code write the following lines. 👇</p>
<p><strong>Note:</strong> don't forget to write the <code>return</code> word inside your <code>.then</code> handler. Otherwise, it won't work properly. If you're curious, try removing the return once we finish the steps:</p>
<pre><code class="lang-javascript">order(<span class="hljs-number">2000</span>,<span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.Fruits[<span class="hljs-number">0</span>]}</span> was selected`</span>))

.then(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-keyword">return</span> order(<span class="hljs-number">0000</span>,<span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'production has started'</span>))
})
</code></pre>
<p>And here's the result: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qhhjaakbi6zshxhi6afy.png" alt="Alt Text" width="759" height="214" loading="lazy"></p>
<p>Using the same system, let's finish our project:👇</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// step 1</span>
order(<span class="hljs-number">2000</span>,<span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.Fruits[<span class="hljs-number">0</span>]}</span> was selected`</span>))

<span class="hljs-comment">// step 2</span>
.then(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-keyword">return</span> order(<span class="hljs-number">0000</span>,<span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'production has started'</span>))
})

<span class="hljs-comment">// step 3</span>
.then(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-keyword">return</span> order(<span class="hljs-number">2000</span>, <span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Fruit has been chopped"</span>))
})

<span class="hljs-comment">// step 4</span>
.then(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-keyword">return</span> order(<span class="hljs-number">1000</span>, <span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.liquid[<span class="hljs-number">0</span>]}</span> and <span class="hljs-subst">${stocks.liquid[<span class="hljs-number">1</span>]}</span> added`</span>))
})

<span class="hljs-comment">// step 5</span>
.then(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-keyword">return</span> order(<span class="hljs-number">1000</span>, <span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"start the machine"</span>))
})

<span class="hljs-comment">// step 6</span>
.then(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-keyword">return</span> order(<span class="hljs-number">2000</span>, <span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`ice cream placed on <span class="hljs-subst">${stocks.holder[<span class="hljs-number">1</span>]}</span>`</span>))
})

<span class="hljs-comment">// step 7</span>
.then(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-keyword">return</span> order(<span class="hljs-number">3000</span>, <span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.toppings[<span class="hljs-number">0</span>]}</span> as toppings`</span>))
})

<span class="hljs-comment">// Step 8</span>
.then(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-keyword">return</span> order(<span class="hljs-number">2000</span>, <span class="hljs-function">()=&gt;</span><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Serve Ice Cream"</span>))
})
</code></pre>
<p>Here's the result: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y0d0f4ys83ctnevkbgxs.png" alt="Alt Text" width="740" height="427" loading="lazy"></p>
<h2 id="heading-error-handling">Error handling</h2>
<p>We need a way to handle errors when something goes wrong. But first, we need to understand the promise cycle:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jlm7zwonbxszeaccyohv.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z2ajcu52rxzwq64g81vp.png" alt="Alt Text" width="1006" height="454" loading="lazy">
<em><strong>An illustration of the life of a promise</strong></em></p>
<p>To catch our errors, let's change our variable to false.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> is_shop_open = <span class="hljs-literal">false</span>;
</code></pre>
<p>Which means our shop is closed. We're not selling ice cream to our customers anymore.</p>
<p>To handle this, we use the <code>.catch</code> handler. Just like <code>.then</code>, it also returns a promise, but only when our original promise is rejected.</p>
<p>A small reminder here:</p>
<ul>
<li><code>.then</code> works when a promise is resolved</li>
<li><code>.catch</code> works when a promise is rejected</li>
</ul>
<p>Go down to the very bottom and write the following code:👇</p>
<p>Just remember that there should be nothing between your previous <code>.then</code> handler and the <code>.catch</code> handler.</p>
<pre><code class="lang-javascript">.catch(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Customer left"</span>)
})
</code></pre>
<p>Here's the result:👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lot6engklu29y05q8xyr.png" alt="Alt Text" width="722" height="214" loading="lazy"></p>
<p>A couple things to note about this code:</p>
<ul>
<li>The 1st message is coming from the <code>reject()</code> part of our promise</li>
<li>The 2nd message is coming from the <code>.catch</code> handler</li>
</ul>
<h2 id="heading-how-to-use-the-finally-handler">How to use the .finally() handler</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gdq3i0agj4volq46ycue.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>There's something called the <code>finally</code> handler which works regardless of whether our promise was resolved or rejected.</p>
<p><strong>For example:</strong> whether we serve no customers or 100 customers, our shop will close at the end of the day</p>
<p>If you're curious to test this, come at very bottom and write this code: 👇</p>
<pre><code class="lang-javascript">.finally(<span class="hljs-function">()=&gt;</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"end of day"</span>)
})
</code></pre>
<p>The result:👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t2j3jf2uofip1d6y2rtt.png" alt="Alt Text" width="731" height="256" loading="lazy"></p>
<p>Everyone, please welcome Async / Await~</p>
<h1 id="heading-how-does-async-await-work-in-javascript">How Does Async / Await Work in JavaScript?</h1>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ra7483f90b69pjl2cbae.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>This is supposed to be the better way to write promises and it helps us keep our code simple and clean.</p>
<p>All you have to do is write the word <code>async</code> before any regular function and it becomes a promise.</p>
<h2 id="heading-but-first-take-a-break">But first, take a break</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4vujyfxz7dg41jhjtcrx.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>Let's have a look:👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17f08ygj1odk28hgl9eq.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<h2 id="heading-promises-vs-asyncawait-in-javascript">Promises vs Async/Await in JavaScript</h2>
<p>Before async/await, to make a promise we wrote this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">order</span>(<span class="hljs-params"></span>)</span>{
   <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>( <span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span>{

    <span class="hljs-comment">// Write code here</span>
   } )
}
</code></pre>
<p>Now using async/await, we write one like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//👇 the magical keyword</span>
 <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">order</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Write code here</span>
 }
</code></pre>
<h2 id="heading-but-wait-2">But wait......</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t1pjzw6zl0h21tyyh9u3.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>You need to understand -&gt;</p>
<ul>
<li>How to use the <code>try</code> and <code>catch</code> keywords</li>
<li>How to use the await keyword</li>
</ul>
<h2 id="heading-how-to-use-the-try-and-catch-keywords">How to use the Try and Catch keywords</h2>
<p>We use the <code>try</code> keyword to run our code while we use <code>catch</code> to catch our errors. It's the same concept we saw when we looked at promises.</p>
<p>Let's see a comparison. We'll see a small demo of the format, then we'll start coding.</p>
<h3 id="heading-promises-in-js-gt-resolve-or-reject">Promises in JS -&gt; resolve or reject</h3>
<p>We used resolve and reject in promises like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">kitchen</span>(<span class="hljs-params"></span>)</span>{

  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span> (<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>)=&gt;</span>{
    <span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
       resolve(<span class="hljs-string">"promise is fulfilled"</span>)
    }

    <span class="hljs-keyword">else</span>{
        reject(<span class="hljs-string">"error caught here"</span>)
    }
  })
}

kitchen()  <span class="hljs-comment">// run the code</span>
.then()    <span class="hljs-comment">// next step</span>
.then()    <span class="hljs-comment">// next step</span>
.catch()   <span class="hljs-comment">// error caught here</span>
.finally() <span class="hljs-comment">// end of the promise [optional]</span>
</code></pre>
<h3 id="heading-async-await-in-js-gt-try-catch">Async / Await in JS -&gt; try, catch</h3>
<p>When we're using async/await, we use this format:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//👇 Magical keyword</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">kitchen</span>(<span class="hljs-params"></span>)</span>{

   <span class="hljs-keyword">try</span>{
<span class="hljs-comment">// Let's create a fake problem      </span>
      <span class="hljs-keyword">await</span> abc;
   }

   <span class="hljs-keyword">catch</span>(error){
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"abc does not exist"</span>, error)
   }

   <span class="hljs-keyword">finally</span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Runs code anyways"</span>)
   }
}

kitchen()  <span class="hljs-comment">// run the code</span>
</code></pre>
<p>Don't panic, we'll discuss the <code>await</code> keyword next.</p>
<p>Now hopefully you understand the difference between promises and Async / Await.</p>
<h2 id="heading-how-to-use-javascripts-await-keyword">How to Use JavaScript's Await Keyword</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fry577xha7313ead96xy.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>The keyword <code>await</code> makes JavaScript wait until a promise settles and returns its result.</p>
<h3 id="heading-how-to-use-the-await-keyword-in-javascript">How to use the await keyword in JavaScript</h3>
<p>Let's go back to our ice cream shop. We don't know which topping a customer might prefer, chocolate or peanuts. So we need to stop our machine and go and ask our customer what they'd like on their ice cream.</p>
<p>Notice here that only our kitchen is stopped, but our staff outside the kitchen will still do things like:</p>
<ul>
<li>doing the dishes</li>
<li>cleaning the tables</li>
<li>taking orders, and so on.</li>
</ul>
<h2 id="heading-an-await-keyword-code-example">An Await Keyword Code Example</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8r5w5aapofalnq882wat.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>Let's create a small promise to ask which topping to use. The process takes three seconds.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toppings_choice</span> (<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{

      resolve( <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"which topping would you love?"</span>) )

    },<span class="hljs-number">3000</span>)
  })
}
</code></pre>
<p>Now, let's create our kitchen function with the async keyword first.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">kitchen</span>(<span class="hljs-params"></span>)</span>{

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"A"</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"B"</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"C"</span>)

  <span class="hljs-keyword">await</span> toppings_choice()

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"D"</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"E"</span>)

}

<span class="hljs-comment">// Trigger the function</span>

kitchen();
</code></pre>
<p>Let's add other tasks below the <code>kitchen()</code> call.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"doing the dishes"</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"cleaning the tables"</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"taking orders"</span>)
</code></pre>
<p>And here's the result:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y0dr669gewtrrd5fd86p.png" alt="Alt Text" width="833" height="453" loading="lazy"></p>
<p>We are literally going outside our kitchen to ask our customer, "what is your topping choice?" In the mean time, other things still get done.</p>
<p>Once, we get their topping choice, we enter the kitchen and finish the job.</p>
<h3 id="heading-small-note">Small note</h3>
<p>When using Async/ Await, you can also use the <code>.then</code>, <code>.catch</code>, and <code>.finally</code>  handlers as well which are a core part of promises.</p>
<h3 id="heading-lets-open-our-ice-cream-shop-again">Let's open our Ice cream shop again</h3>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzw8gp721oecwo2b3l6s.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>We're gonna create two functions -&gt;</p>
<ul>
<li><code>kitchen</code>: to make ice cream</li>
<li><code>time</code>: to assign the amount of time each small task will take.</li>
</ul>
<p>Let's start! First, create the time function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> is_shop_open = <span class="hljs-literal">true</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">time</span>(<span class="hljs-params">ms</span>) </span>{

   <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>( <span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {

      <span class="hljs-keyword">if</span>(is_shop_open){
         <span class="hljs-built_in">setTimeout</span>(resolve,ms);
      }

      <span class="hljs-keyword">else</span>{
         reject(<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Shop is closed"</span>))
      }
    });
}
</code></pre>
<p>Now, let's create our kitchen:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">kitchen</span>(<span class="hljs-params"></span>)</span>{
   <span class="hljs-keyword">try</span>{

     <span class="hljs-comment">// instruction here</span>
   }

   <span class="hljs-keyword">catch</span>(error){
    <span class="hljs-comment">// error management here</span>
   }
}

<span class="hljs-comment">// Trigger</span>
kitchen();
</code></pre>
<p>Let's give small instructions and test if our kitchen function is working or not:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">kitchen</span>(<span class="hljs-params"></span>)</span>{
   <span class="hljs-keyword">try</span>{

<span class="hljs-comment">// time taken to perform this 1 task</span>
     <span class="hljs-keyword">await</span> time(<span class="hljs-number">2000</span>)
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.Fruits[<span class="hljs-number">0</span>]}</span> was selected`</span>)
   }

   <span class="hljs-keyword">catch</span>(error){
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Customer left"</span>, error)
   }

   <span class="hljs-keyword">finally</span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Day ended, shop closed"</span>)
    }
}

<span class="hljs-comment">// Trigger</span>
kitchen();
</code></pre>
<p>The result looks like this when the shop is open: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lptup827qau72e83deuv.png" alt="Alt Text" width="698" height="239" loading="lazy"></p>
<p>The result looks like this when the shop is closed: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8pjz1qlw58ap8pq7crz.png" alt="Alt Text" width="692" height="254" loading="lazy"></p>
<p>So far so good.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cnkgk63x51wth2byxzfe.png" alt="Alt Text" width="1006" height="454" loading="lazy"></p>
<p>Let's complete our project.</p>
<p>Here's the list of our tasks again: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7wthn0jr5vw7vb02e4qg.png" alt="Alt Text" width="2353" height="1374" loading="lazy">
<em><strong>Chart contains steps to make ice cream</strong></em></p>
<p>First, open our shop</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> is_shop_open = <span class="hljs-literal">true</span>;
</code></pre>
<p>Now write the steps inside our <code>kitchen()</code> function: 👇</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">kitchen</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">try</span>{
    <span class="hljs-keyword">await</span> time(<span class="hljs-number">2000</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.Fruits[<span class="hljs-number">0</span>]}</span> was selected`</span>)

    <span class="hljs-keyword">await</span> time(<span class="hljs-number">0000</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"production has started"</span>)

    <span class="hljs-keyword">await</span> time(<span class="hljs-number">2000</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"fruit has been chopped"</span>)

    <span class="hljs-keyword">await</span> time(<span class="hljs-number">1000</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.liquid[<span class="hljs-number">0</span>]}</span> and <span class="hljs-subst">${stocks.liquid[<span class="hljs-number">1</span>]}</span> added`</span>)

    <span class="hljs-keyword">await</span> time(<span class="hljs-number">1000</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"start the machine"</span>)

    <span class="hljs-keyword">await</span> time(<span class="hljs-number">2000</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`ice cream placed on <span class="hljs-subst">${stocks.holder[<span class="hljs-number">1</span>]}</span>`</span>)

    <span class="hljs-keyword">await</span> time(<span class="hljs-number">3000</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${stocks.toppings[<span class="hljs-number">0</span>]}</span> as toppings`</span>)

    <span class="hljs-keyword">await</span> time(<span class="hljs-number">2000</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Serve Ice Cream"</span>)
    }

    <span class="hljs-keyword">catch</span>(error){
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"customer left"</span>)
    }
}
</code></pre>
<p>And here's the result: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qs9yccq9209u7m9lquju.png" alt="Alt Text" width="1221" height="607" loading="lazy"></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Congratulations for reading until the end! In this article you've learned: </p>
<ul>
<li>The difference between synchronous and asynchronous systems</li>
<li>Mechanisms of asynchronous JavaScript using 3 techniques (callbacks, promises, and Async/ Await)</li>
</ul>
<p>Here's your medal for reading until the end. ❤️</p>
<h3 id="heading-suggestions-and-criticisms-are-highly-appreciated">Suggestions and criticisms are highly appreciated ❤️</h3>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/usxsz1lstuwry3jlly4d.png" alt="Alt Text" width="1000" height="245" loading="lazy"></p>
<p><strong>YouTube <a target="_blank" href="https://youtube.com/c/joyshaheb">/ Joy Shaheb</a></strong></p>
<p><strong>LinkedIn <a target="_blank" href="https://www.linkedin.com/in/joyshaheb/">/ JoyShaheb</a></strong></p>
<p><strong>Twitter <a target="_blank" href="https://twitter.com/JoyShaheb">/ JoyShaheb</a></strong></p>
<p><strong>Instagram <a target="_blank" href="https://www.instagram.com/joyshaheb/">/ JoyShaheb</a></strong></p>
<h1 id="heading-credits">Credits</h1>
<ul>
<li><a target="_blank" href="https://www.freepik.com/user/collections/promises-article/2046500">Collection of all the images used</a></li>
<li><a target="_blank" href="https://www.flaticon.com/packs/unicorn-4">Unicorns</a>, <a target="_blank" href="https://www.flaticon.com/packs/kitty-avatars-3">kitty avatar</a></li>
<li><a target="_blank" href="https://www.pexels.com/photo/brown-tabby-cat-with-slice-of-loaf-bread-on-head-4587955/">tabby cat</a>, <a target="_blank" href="https://www.pexels.com/photo/young-female-astrologist-predicting-future-with-shining-ball-6658693/">Astrologist Woman</a>, <a target="_blank" href="https://www.pexels.com/photo/woman-in-white-dress-holding-white-flower-bouquet-3981511/">girl-holding-flower</a></li>
<li><a target="_blank" href="https://www.vecteezy.com/vector-art/180695-people-mind-emotion-character-cartoon-vector-illustration">Character emotions</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An Introduction to JavaScript's queueMicrotask ]]>
                </title>
                <description>
                    <![CDATA[ By Ujjwal Gupta Introduction queueMicrotask is a new browser API which can be used to convert your synchronous code into async: queueMicrotask(() => {     console.log('hey i am executed asychronously by queueMicrotask'); }); It's similar to what we ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/queuemicrotask/</link>
                <guid isPermaLink="false">66d4617573634435aafceff9</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Browsers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 08 Sep 2019 18:11:45 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9ca077740569d1a4ca48d3.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ujjwal Gupta</p>
<h2 id="heading-introduction">Introduction</h2>
<p><strong>queueMicrotask</strong> is a new browser API which can be used to convert your synchronous code into async:</p>
<pre><code class="lang-javascript">queueMicrotask(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hey i am executed asychronously by queueMicrotask'</span>);
});
</code></pre>
<p>It's similar to what we were doing using setTimeout:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hey i am executed asychronously by setTimeout'</span>);
}, <span class="hljs-number">0</span>);
</code></pre>
<p>So what's the use of <strong>queueMicrotask</strong> when we already have <strong>setTimeout</strong> ?</p>
<blockquote>
<p><strong>queueMicrotask</strong> adds the function (task) into a queue and each function is executed one by one (FIFO) after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event loop.</p>
</blockquote>
<p>Basically the tasks of <strong>queueMicrotask</strong> are executed just after current callstack is empty before passing the execution to the event loop.</p>
<blockquote>
<p>In the case of <strong>setTimeout</strong>, each task is executed from the event queue, after control is given to the event loop.</p>
</blockquote>
<p>So if we execute <strong>setTimeout</strong> first and then <strong>queueMicrotask</strong>, which will be called first?  Execute the below code and check out yourself:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hey i am executed asychronously by setTimeout'</span>);
},<span class="hljs-number">0</span>);

queueMicrotask(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hey i am executed asychronously by queueMicrotask'</span>);
});
</code></pre>
<p>Node.js does the same thing with "process.nextTick".</p>
<h2 id="heading-when-to-use-it">When to Use <strong>It</strong></h2>
<p>There is no rule for when to use <strong>queueMicrotask,</strong> but it can be used cleverly to run a piece of code without stopping the current execution.</p>
<p>For example, let's say we have an array where we are maintaining list of values. After every value is inserted, we sort the array so that searching for values is faster.</p>
<pre><code><span class="hljs-keyword">var</span> arr=[];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">value</span>)</span>{
  arr.push(value);
  arr.sort();
}
</code></pre><p>However, searching for an element is done whenever someone uses a search input box. This means the event handler will be called after control is transferred to the event loop, so sorting the data blocks the execution of other important synchronous code.</p>
<p>Here's how we can use <strong>queueMicrotask</strong> to improve our code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> arr = [];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">value</span>) </span>{
  arr.push(value);
  queueMicrotask(<span class="hljs-function">() =&gt;</span> {
    arr.sort();
  })
}
</code></pre>
<h2 id="heading-references">References</h2>
<ul>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask">https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Why Naked Promises Are Not Safe For Work - and What to Do Instead ]]>
                </title>
                <description>
                    <![CDATA[ By swyx This article goes through my personal journey of discovery and struggle adopting the conventional wisdom as it pertains to asynchronous work on the frontend. With any luck, you will come away with at least a deeper appreciation of 3 tricky ca... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/naked-promises-are-not-safe-for-work/</link>
                <guid isPermaLink="false">66d4615055db48792eed3fa9</guid>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 15 Aug 2019 19:01:58 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9ca0d5740569d1a4ca4b14.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By swyx</p>
<p>This article goes through my personal journey of discovery and struggle adopting the conventional wisdom as it pertains to asynchronous work on the frontend. With any luck, you will come away with at least a deeper appreciation of 3 tricky cases to handle when crossing the synchronous to asynchronous boundary. And we'll possibly even conclude that you will never want to manually account for these edge cases yourself ever again.</p>
<p>My examples are in React, but I believe they are universal principles that have parallels in all frontend apps.</p>
<h2 id="heading-what-is-a-naked-promise-anyway">What is a "Naked Promise" anyway?</h2>
<p>To do anything interesting in our app, we will probably use an asynchronous API at some point. In JavaScript, Promises have overtaken callbacks to be the asynchronous API of choice (especially as every platform has come to accept <code>async</code>/<code>await</code>). They have even become part of the "Web platform" - here's a typical example using the Promise-based <code>fetch</code> API in all modern browsers:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [msg, setMsg] = React.useState(<span class="hljs-string">'click the button'</span>)
  <span class="hljs-keyword">const</span> handler = <span class="hljs-function">() =&gt;</span>
    fetch(<span class="hljs-string">'https://myapi.com/'</span>)
      .then(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x.json())
      .then(<span class="hljs-function">(<span class="hljs-params">{ msg }</span>) =&gt;</span> setMsg(msg))

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>message: {msg}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handler}</span>&gt;</span> click meeee<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>Here our button's <code>handler</code> function returns a "naked" Promise - it isn't wrapped by anything, it is just invoked outright so it can do fetch data and set state. This is an extremely common pattern taught in all introductions. This is fine for demo apps, however in the real world users often run into many edge cases this pattern conveniently forgets to account for.</p>
<h2 id="heading-promises-fail-the-error-state">Promises Fail: The Error State</h2>
<p>Promises fail. It is too easy to only code for the "happy path" where your network is always working and your API always returns a successful result. Most devs are all too familiar with the uncaught exceptions that arise only in production that make your app seem like it didn't work or is stuck in some kind of loading state. There are <a target="_blank" href="https://github.com/xjamundx/eslint-plugin-promise/blob/HEAD/docs/rules/catch-or-return.md">ESlint rules to ensure you write <code>.catch</code></a> handlers on your promises.</p>
<p>This only helps for promises you chain with a <code>.then</code>, but doesn't help when passing a promise to a library you don't control, or when you just call the promise outright.</p>
<p>Either way, ultimately the responsibility for displaying the error state will fall on you, and will look something like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [msg, setMsg] = React.useState(<span class="hljs-string">'click the button'</span>)
  <span class="hljs-keyword">const</span> [err, setErr] = React.useState(<span class="hljs-literal">null</span>)
  <span class="hljs-keyword">const</span> handler = <span class="hljs-function">() =&gt;</span> {
    setErr(<span class="hljs-literal">null</span>)
    fetch(<span class="hljs-string">'https://myapi.com/'</span>)
      .then(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x.json())
      .then(<span class="hljs-function">(<span class="hljs-params">{ msg }</span>) =&gt;</span> setMsg(msg))
      .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> setErr(err))
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>message: {msg}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        {err &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">pre</span>&gt;</span>{err}<span class="hljs-tag">&lt;/<span class="hljs-name">pre</span>&gt;</span>}
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handler}</span>&gt;</span>click meeee<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>We now have two states to handle for every asynchronous operation in our app!</p>
<h2 id="heading-promises-in-progress-the-loading-state">Promises in Progress: The Loading State</h2>
<p>When pinging your APIs on your local machine (<a target="_blank" href="https://alligator.io/nodejs/solve-cors-once-and-for-all-netlify-dev/">for example, with Netlify Dev</a>), it is pretty common to get rapid responses. However, this ignores the fact that API latency may be a good deal slower in real world, especially mobile, environments. When the button is clicked, the promise fires, however there is no visual feedback at all in the UI to tell the user that the click has been registered and the data is inflight. So users often click again, in case they misclicked, and generate yet more API requests. This is a terrible user experience and there is no reason for writing click handlers this way except that it is the default.</p>
<p>You can make your app more responsive (and less frustrating) by offering some form of loading state:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [msg, setMsg] = React.useState(<span class="hljs-string">'click the button'</span>)
  <span class="hljs-keyword">const</span> [loading, setLoading] = React.useState(<span class="hljs-literal">false</span>)
  <span class="hljs-keyword">const</span> handler = <span class="hljs-function">() =&gt;</span> {
    setLoading(<span class="hljs-literal">true</span>)
    fetch(<span class="hljs-string">'https://myapi.com/'</span>)
      .then(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x.json())
      .then(<span class="hljs-function">(<span class="hljs-params">{ msg }</span>) =&gt;</span> setMsg(msg))
      .finally(<span class="hljs-function">() =&gt;</span> setLoading(<span class="hljs-literal">false</span>))
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>message: {msg}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        {loading &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">pre</span>&gt;</span>loading...<span class="hljs-tag">&lt;/<span class="hljs-name">pre</span>&gt;</span>}
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handler}</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{loading}</span>&gt;</span>
          click meeee
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>We now have <strong>three</strong> states to handle for every asynchronous operation in our app: result, loading, and error state! Oy vey.</p>
<h2 id="heading-promises-are-dumb-the-components-state">Promises are dumb: The Component's State</h2>
<p>Once promises fire off, they cannot be canceled. This was a <a target="_blank" href="https://medium.com/@benlesh/promise-cancellation-is-dead-long-live-promise-cancellation-c6601f1f5082">controversial decision</a> at the time, and while platform specific workarounds like <a target="_blank" href="https://developers.google.com/web/updates/2017/09/abortable-fetch">abortable fetch</a> exist, it's clear we will never get cancelable promises in the language itself. This causes issues when we fire off promises and then no longer need them, for example when the component it is supposed to update has unmounted (because the user has navigated somewhere else).</p>
<p>In React, this causes a development-only error like:</p>
<pre><code class="lang-bash">Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

<span class="hljs-comment"># or</span>

Warning: Can’t call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak <span class="hljs-keyword">in</span> your application. To fix, cancel all subscriptions and asynchronous tasks <span class="hljs-keyword">in</span> the componentWillUnmount method.
</code></pre>
<p>You can avoid this memory leak by tracking the mount state of a component:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [msg, setMsg] = React.useState(<span class="hljs-string">'click the button'</span>)
  <span class="hljs-keyword">const</span> isMounted = React.useRef(<span class="hljs-literal">true</span>)
  <span class="hljs-keyword">const</span> handler = <span class="hljs-function">() =&gt;</span> {
    setLoading(<span class="hljs-literal">true</span>)
    fetch(<span class="hljs-string">'https://myapi.com/'</span>)
      .then(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x.json())
      .then(<span class="hljs-function">(<span class="hljs-params">{ msg }</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (isMounted.current) {
          setMsg(msg)
        }
      })
  }
  React.useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> (isMounted.current = <span class="hljs-literal">false</span>)
  })

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>message: {msg}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handler}</span>&gt;</span>click meeee<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>We've used a Ref here, as <a target="_blank" href="https://medium.com/@pshrmn/react-hook-gotchas-e6ca52f49328">it is closer to the mental model of an instance variable</a>, but you won't notice too much of a difference if you <code>useState</code> instead.</p>
<p>Longtime React users will also remember that <a target="_blank" href="https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html">isMounted is an antipattern</a>, however tracking <code>_isMounted</code> as an instance variable is still recommended if you don't use cancellable promises. (Which is ALL. THE. TIME.)</p>
<p>For those keeping count, we're now at <strong>four</strong> states needing to be tracked for a single async operation in a component.</p>
<h2 id="heading-solution-just-wrap-it">Solution: Just Wrap It</h2>
<p>The problem should be pretty clear by now:</p>
<p>In a simple demo, "naked" promises work fine.</p>
<p>In a production situation, you're going to want to implement all these error handling, loading, and mounting tracker states. Again. And again. And again.</p>
<p>Sounds like a good place to use a library, doesn't it?</p>
<p>Fortunately, quite a few exist.</p>
<p><code>react-async</code>'s <code>useAsync</code> hook lets you pass a <code>promiseFn</code>, together with several handy <a target="_blank" href="https://www.npmjs.com/package/react-async#options">options</a> to add callbacks and other advanced usecases:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useAsync } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-async'</span>

<span class="hljs-keyword">const</span> loadCustomer = <span class="hljs-keyword">async</span> ({ customerId }, { signal }) =&gt; {
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`/api/customers/<span class="hljs-subst">${customerId}</span>`</span>, { signal })
  <span class="hljs-keyword">if</span> (!res.ok) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(res)
  <span class="hljs-keyword">return</span> res.json()
}

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { data, error, isLoading } = useAsync({ <span class="hljs-attr">promiseFn</span>: loadCustomer, <span class="hljs-attr">customerId</span>: <span class="hljs-number">1</span> })
  <span class="hljs-keyword">if</span> (isLoading) <span class="hljs-keyword">return</span> <span class="hljs-string">'Loading...'</span>
  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="hljs-string">`Something went wrong: <span class="hljs-subst">${error.message}</span>`</span>
  <span class="hljs-keyword">if</span> (data)
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>Loaded some data:<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">pre</span>&gt;</span>{JSON.stringify(data, null, 2)}<span class="hljs-tag">&lt;/<span class="hljs-name">pre</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>
}
</code></pre>
<p>It also includes a handy <code>useFetch</code> hook you can use in place of the native <code>fetch</code> implementation.</p>
<p><code>react-use</code> also offers <a target="_blank" href="https://github.com/streamich/react-use/blob/master/docs/useAsync.md">a simple <code>useAsync</code> implementation</a>, where you just pass in a promise (aka <code>async</code> function):</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useAsync } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-use'</span>

<span class="hljs-keyword">const</span> Demo = <span class="hljs-function">(<span class="hljs-params">{ url }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> state = useAsync(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url)
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> response.text()
    <span class="hljs-keyword">return</span> result
  }, [url])

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {state.loading ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      ) : state.error ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Error: {state.error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      ) : (
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Value: {state.value}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      )}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>Lastly, Daishi Kato's <a target="_blank" href="https://github.com/dai-shi/react-hooks-async"><code>react-hooks-async</code></a> also offers a very nice <code>abort</code> controller for any promises:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-keyword">import</span> { useFetch } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hooks-async'</span>

<span class="hljs-keyword">const</span> UserInfo = <span class="hljs-function">(<span class="hljs-params">{ id }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> url = <span class="hljs-string">`https://reqres.in/api/users/<span class="hljs-subst">${id}</span>?delay=1`</span>
  <span class="hljs-keyword">const</span> { pending, error, result, abort } = useFetch(url)
  <span class="hljs-keyword">if</span> (pending)
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        Loading...<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{abort}</span>&gt;</span>Abort<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
  <span class="hljs-keyword">if</span> (error)
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        Error: {error.name} {error.message}
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
  <span class="hljs-keyword">if</span> (!result) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>No result<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>First Name: {result.data.first_name}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
}

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">UserInfo</span> <span class="hljs-attr">id</span>=<span class="hljs-string">{</span>'<span class="hljs-attr">1</span>'} /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">UserInfo</span> <span class="hljs-attr">id</span>=<span class="hljs-string">{</span>'<span class="hljs-attr">2</span>'} /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)
</code></pre>
<p>You can also choose to <a target="_blank" href="https://medium.com/@benlesh/promise-cancellation-is-dead-long-live-promise-cancellation-c6601f1f5082">use Observables</a>, either by wrapping your Promise in one or just using them outright.</p>
<p>In any case, you can see the emergent pattern that <strong>you'll always want to wrap your promises</strong> to use them safely in a production environment. At a meta-level, what's going on here is JavaScript lets you call both synchronous and asynchronous code with the exact same API, which is an unfortunate design constraint. It means that we need wrappers to safely translate asynchronous execution to synchronous variables we care about, especially in an immediate-mode rendering paradigm like React. We have to choose to either write these ourselves every time, or adopt a library.</p>
<p>If you have any further comments and edge cases that I haven't thought of, please <a target="_blank" href="https://twitter.com/swyx">get in touch!</a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
