<?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[ async/await - 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[ async/await - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 29 May 2026 23:04:06 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/asyncawait/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ When to Use Async/Await vs Promises in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is an asynchronous programming language, which means it can handle multiple operations at the same time without blocking the main thread. When working with asynchronous operations like API calls, file reading, or database queries, you have... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/when-to-use-asyncawait-vs-promises-in-javascript/</link>
                <guid isPermaLink="false">68644a229f16e7c95c9c9538</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promise methods ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Henry Adepegba ]]>
                </dc:creator>
                <pubDate>Tue, 01 Jul 2025 20:50:42 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1751402055038/f0954bc1-e528-4add-a659-4750c6d8eb33.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is an asynchronous programming language, which means it can handle multiple operations at the same time without blocking the main thread. When working with asynchronous operations like API calls, file reading, or database queries, you have two main approaches: Promises and Async/Await.</p>
<p>In this article, you will learn the differences between these two approaches, when to use each one, and how to make the right choice for your specific use case.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-are-asynchronous-operations">What Are Asynchronous Operations?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-promises">What Are Promises?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-asyncawait">What Is Async/Await?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-practical-examples-promises-vs-asyncawait">Practical Examples: Promises vs Async/Await</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-promises">When to Use Promises</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-asyncawait">When to Use Async/Await</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-performance-considerations">Performance Considerations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-error-handling-patterns">Error Handling Patterns</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices">Best Practices</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-making-the-right-choice">Making the Right Choice</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-what-are-asynchronous-operations">What Are Asynchronous Operations?</h2>
<p>Before explaining what Promises and Async/Await mean, it is important to understand what asynchronous operations are.</p>
<p><strong>Synchronous operations</strong> execute one after another, blocking the next operation until the current one completes. Here’s an example in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"First"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Second"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Third"</span>);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// First</span>
<span class="hljs-comment">// Second</span>
<span class="hljs-comment">// Third</span>
</code></pre>
<p><strong>Asynchronous operations</strong>, on the other hand, can start an operation and continue executing other code while waiting for the first operation to complete. Here’s an example in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"First"</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">"Second (after 2 seconds)"</span>);
}, <span class="hljs-number">2000</span>);

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

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// First</span>
<span class="hljs-comment">// Third</span>
<span class="hljs-comment">// Second (after 2 seconds)</span>
</code></pre>
<p>In this example, <code>setTimeout()</code> is an asynchronous function that schedules code to run after a specified delay without blocking the execution of subsequent code.</p>
<h2 id="heading-what-are-promises">What Are Promises?</h2>
<p>A <strong>Promise</strong> is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation. Think of it as a placeholder for a value that will be available in the future.</p>
<h3 id="heading-promise-states">Promise States</h3>
<p>A Promise can be in one of three states:</p>
<ol>
<li><p><strong>Pending</strong>: The initial state – the operation hasn't been completed yet</p>
</li>
<li><p><strong>Fulfilled (Resolved)</strong>: The operation completed successfully</p>
</li>
<li><p><strong>Rejected</strong>: The operation failed</p>
</li>
</ol>
<h3 id="heading-basic-promise-syntax">Basic Promise Syntax</h3>
<p>Here's how you create and use a basic Promise:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating 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-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">// Simulate 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">"Operation completed successfully!"</span>);
        } <span class="hljs-keyword">else</span> {
            reject(<span class="hljs-string">"Operation failed!"</span>);
        }
    }, <span class="hljs-number">2000</span>);
});

<span class="hljs-comment">// Using the Promise</span>
myPromise
    .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">// "Operation completed successfully!"</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>Let's break down this code:</p>
<ul>
<li><p><code>new Promise()</code> creates a new Promise object</p>
</li>
<li><p>The Promise constructor takes a function with two parameters: <code>resolve</code> and <code>reject</code></p>
</li>
<li><p><code>resolve()</code> is called when the operation succeeds</p>
</li>
<li><p><code>reject()</code> is called when the operation fails</p>
</li>
<li><p><code>.then()</code> handles the successful case</p>
</li>
<li><p><code>.catch()</code> handles the error case</p>
</li>
</ul>
<h3 id="heading-chaining-promises">Chaining Promises</h3>
<p>Promise chaining is a powerful technique that allows you to link multiple asynchronous operations together in a sequence. When you want to perform multiple operations where each depends on the result of the previous one, promise chaining provides an elegant solution. You can chain multiple Promises together using <code>.then()</code>:</p>
<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-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            resolve({ <span class="hljs-attr">id</span>: userId, <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span> });
        }, <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">user</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-attr">title</span>: <span class="hljs-string">"Post 1"</span>, <span class="hljs-attr">author</span>: user.name },
                { <span class="hljs-attr">title</span>: <span class="hljs-string">"Post 2"</span>, <span class="hljs-attr">author</span>: user.name }
            ]);
        }, <span class="hljs-number">1000</span>);
    });
}

<span class="hljs-comment">// Chaining Promises</span>
fetchUserData(<span class="hljs-number">123</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"User:"</span>, user);
        <span class="hljs-keyword">return</span> fetchUserPosts(user);
    })
    .then(<span class="hljs-function">(<span class="hljs-params">posts</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Posts:"</span>, posts);
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error:"</span>, error);
    });
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>fetchUserData()</code> returns a Promise that resolves with user information</p>
</li>
<li><p><code>fetchUserPosts()</code> returns a Promise that resolves with the user's posts</p>
</li>
<li><p>We chain these operations using <code>.then()</code></p>
</li>
<li><p>Each <code>.then()</code> receives the resolved value from the previous Promise</p>
</li>
</ul>
<h4 id="heading-downsides-of-promise-chaining">Downsides of Promise Chaining:</h4>
<p>While promise chaining is powerful, it does have some potential drawbacks:</p>
<ol>
<li><p><strong>"Callback Hell" in disguise</strong>: Complex chains can become difficult to read and debug, especially with nested logic</p>
</li>
<li><p><strong>Complex error handling</strong>: Each step in the chain needs proper error handling, and errors can propagate in unexpected ways</p>
</li>
<li><p><strong>Debugging challenges</strong>: Stack traces through promise chains can be harder to follow</p>
</li>
<li><p><strong>Mixing synchronous and asynchronous logic</strong>: It can be tempting to put synchronous operations inside .then() blocks, which can lead to confusion</p>
</li>
</ol>
<h2 id="heading-what-is-asyncawait">What Is Async/Await?</h2>
<p><strong>Async/Await</strong> is syntactic sugar built on top of Promises. It allows you to write asynchronous code that looks and behaves more like synchronous code, making it easier to read and understand.</p>
<h3 id="heading-basic-asyncawait-syntax">Basic Async/Await Syntax</h3>
<p>Here's the same Promise example rewritten using Async/Await:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating an async function</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">performOperation</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> myPromise;
        <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// "Operation completed successfully!"</span>
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(error);
    }
}

performOperation();
</code></pre>
<p>Let's break down this code:</p>
<ul>
<li><p>The <code>async</code> keyword before a function declaration makes it an asynchronous function</p>
</li>
<li><p>The <code>await</code> keyword pauses the function execution until the Promise resolves</p>
</li>
<li><p>The <code>try/catch</code> blocks handle errors, similar to <code>.catch()</code> in Promises</p>
</li>
</ul>
<h3 id="heading-converting-promise-chains-to-asyncawait">Converting Promise Chains to Async/Await</h3>
<p>Here's the previous chaining example using Async/Await:</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">getUserDataAndPosts</span>(<span class="hljs-params">userId</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUserData(userId);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"User:"</span>, user);

        <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> fetchUserPosts(user);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Posts:"</span>, posts);

        <span class="hljs-keyword">return</span> posts;
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error:"</span>, error);
        <span class="hljs-keyword">throw</span> error; <span class="hljs-comment">// Re-throw the error if needed</span>
    }
}

getUserDataAndPosts(<span class="hljs-number">123</span>);
</code></pre>
<p>This code is much more readable and follows a linear flow that's easier to understand.</p>
<h2 id="heading-practical-examples-promises-vs-asyncawait">Practical Examples: Promises vs Async/Await</h2>
<p>Let's compare both approaches with real-world scenarios.</p>
<h3 id="heading-example-1-making-api-calls">Example 1: Making API Calls</h3>
<p><strong>Using Promises:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchDataWithPromises</span>(<span class="hljs-params"></span>) </span>{
    fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</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">'Network response was not ok'</span>);
            }
            <span class="hljs-keyword">return</span> response.json();
        })
        .then(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User data:'</span>, user);
            <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">`https://jsonplaceholder.typicode.com/users/<span class="hljs-subst">${user.id}</span>/posts`</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">posts</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User posts:'</span>, posts);
        })
        .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><strong>Using Async/Await:</strong></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">fetchDataWithAsyncAwait</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> userResponse = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>);

        <span class="hljs-keyword">if</span> (!userResponse.ok) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network response was not ok'</span>);
        }

        <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> userResponse.json();
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User data:'</span>, user);

        <span class="hljs-keyword">const</span> postsResponse = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://jsonplaceholder.typicode.com/users/<span class="hljs-subst">${user.id}</span>/posts`</span>);
        <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> postsResponse.json();
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User posts:'</span>, posts);

    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
    }
}
</code></pre>
<p>The Async/Await version is more readable and follows a natural top-to-bottom flow.</p>
<h3 id="heading-example-2-handling-multiple-asynchronous-operations">Example 2: Handling Multiple Asynchronous Operations</h3>
<p><strong>Using Promises:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processMultipleOperations</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> promise1 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>);
    <span class="hljs-keyword">const</span> promise2 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/2'</span>);
    <span class="hljs-keyword">const</span> promise3 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/3'</span>);

    <span class="hljs-built_in">Promise</span>.all([promise1, promise2, promise3])
        .then(<span class="hljs-function"><span class="hljs-params">responses</span> =&gt;</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.all(responses.map(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json()));
        })
        .then(<span class="hljs-function"><span class="hljs-params">users</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'All users:'</span>, users);
        })
        .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><strong>Using Async/Await:</strong></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">processMultipleOperationsAsync</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> promise1 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>);
        <span class="hljs-keyword">const</span> promise2 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/2'</span>);
        <span class="hljs-keyword">const</span> promise3 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/3'</span>);

        <span class="hljs-keyword">const</span> responses = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all([promise1, promise2, promise3]);
        <span class="hljs-keyword">const</span> users = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all(responses.map(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json()));

        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'All users:'</span>, users);
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
    }
}
</code></pre>
<p>Both approaches use <code>Promise. all()</code> to wait for multiple operations to complete simultaneously.</p>
<h2 id="heading-when-to-use-promises">When to Use Promises</h2>
<p>Promises are still useful in several scenarios:</p>
<h3 id="heading-1-working-with-existing-promise-based-apis">1. Working with Existing Promise-Based APIs</h3>
<p>Popular libraries like Axios, fetch(), and many Node.js modules return Promises.</p>
<p><strong>How to identify promise-based APIs:</strong></p>
<ul>
<li><p>The function returns an object with <code>.then()</code> and <code>.catch()</code> methods</p>
</li>
<li><p>The documentation mentions "returns a Promise"</p>
</li>
<li><p>The function doesn't require a callback parameter</p>
</li>
</ul>
<p>Many libraries and APIs return Promises directly:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Axios library returns Promises</span>
axios.get(<span class="hljs-string">'/api/users'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.data)
    .then(<span class="hljs-function"><span class="hljs-params">users</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(users))
    .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">// fetch() API returns Promises</span>
fetch(<span class="hljs-string">'/api/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));

<span class="hljs-comment">// Node.js fs.promises returns Promises</span>
<span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'fs/promises'</span>;
readFile(<span class="hljs-string">'./config.json'</span>, <span class="hljs-string">'utf8'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">JSON</span>.parse(data))
    .then(<span class="hljs-function"><span class="hljs-params">config</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(config));
</code></pre>
<h3 id="heading-2-functional-programming-patterns">2. Functional Programming Patterns</h3>
<p>Promises are immutable objects that represent future values, making them perfect for functional programming approaches. They can be easily composed, chained, and transformed without side effects. The <code>.then()</code> method essentially maps over the future value, similar to how <code>Array.map()</code> works with collections.</p>
<p>Promises work well with functional programming approaches because they are composable and can be easily passed around as first-class objects:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Functional composition with Promises</span>
<span class="hljs-keyword">const</span> processUsers = <span class="hljs-function">(<span class="hljs-params">userIds</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.all(
        userIds.map(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> fetchUser(id))  <span class="hljs-comment">// Transform each ID to a Promise</span>
    )
    .then(<span class="hljs-function"><span class="hljs-params">users</span> =&gt;</span> users.filter(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.active))  <span class="hljs-comment">// Filter active users</span>
    .then(<span class="hljs-function"><span class="hljs-params">activeUsers</span> =&gt;</span> activeUsers.map(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.email));  <span class="hljs-comment">// Extract emails</span>
};

<span class="hljs-comment">// Pipeline approach</span>
<span class="hljs-keyword">const</span> createUserPipeline = <span class="hljs-function">(<span class="hljs-params">userId</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> fetchUser(userId)
        .then(validateUser)
        .then(enrichUserData)
        .then(formatUserResponse)
        .then(logUserActivity);
};

<span class="hljs-comment">// Composing multiple Promise-returning functions</span>
<span class="hljs-keyword">const</span> compose = <span class="hljs-function">(<span class="hljs-params">...fns</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> 
    fns.reduce(<span class="hljs-function">(<span class="hljs-params">promise, fn</span>) =&gt;</span> promise.then(fn), <span class="hljs-built_in">Promise</span>.resolve(value));

<span class="hljs-keyword">const</span> userProcessor = compose(
    fetchUser,
    validateUser,
    enrichUserData,
    saveUser
);
</code></pre>
<h3 id="heading-3-creating-reusable-promise-utilities">3. Creating Reusable Promise Utilities</h3>
<p>Reusable promise utilities are helper functions that abstract common asynchronous patterns into reusable components. They're particularly useful for cross-cutting concerns like retries, timeouts, rate limiting, and caching. These utilities can be used across different parts of your application without being tied to specific business logic.</p>
<p><strong>When they're useful:</strong></p>
<ul>
<li><p>When you need the same asynchronous pattern in multiple places</p>
</li>
<li><p>For handling common failure scenarios (network timeouts, retries)</p>
</li>
<li><p>When building middleware or interceptors</p>
</li>
<li><p>For performance optimizations like batching or debouncing</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Timeout utility</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">timeout</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</span> =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, ms));
}

<span class="hljs-comment">// Retry utility with exponential backoff</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">retry</span>(<span class="hljs-params">fn, retries = <span class="hljs-number">3</span>, delay = <span class="hljs-number">1000</span></span>) </span>{
    <span class="hljs-keyword">return</span> fn().catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
        <span class="hljs-keyword">if</span> (retries &gt; <span class="hljs-number">0</span>) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Retrying... <span class="hljs-subst">${retries}</span> attempts left`</span>);
            <span class="hljs-keyword">return</span> timeout(delay).then(<span class="hljs-function">() =&gt;</span> retry(fn, retries - <span class="hljs-number">1</span>, delay * <span class="hljs-number">2</span>));
        }
        <span class="hljs-keyword">throw</span> error;
    });
}

<span class="hljs-comment">// Rate limiting utility</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rateLimit</span>(<span class="hljs-params">fn, maxCalls, timeWindow</span>) </span>{
    <span class="hljs-keyword">let</span> calls = [];

    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">...args</span>) </span>{
        <span class="hljs-keyword">const</span> now = <span class="hljs-built_in">Date</span>.now();
        calls = calls.filter(<span class="hljs-function"><span class="hljs-params">time</span> =&gt;</span> now - time &lt; timeWindow);

        <span class="hljs-keyword">if</span> (calls.length &gt;= maxCalls) {
            <span class="hljs-keyword">const</span> waitTime = timeWindow - (now - calls[<span class="hljs-number">0</span>]);
            <span class="hljs-keyword">return</span> timeout(waitTime).then(<span class="hljs-function">() =&gt;</span> fn.apply(<span class="hljs-built_in">this</span>, args));
        }

        calls.push(now);
        <span class="hljs-keyword">return</span> fn.apply(<span class="hljs-built_in">this</span>, args);
    };
}

<span class="hljs-comment">// Usage examples</span>
<span class="hljs-keyword">const</span> apiCall = <span class="hljs-function">() =&gt;</span> fetch(<span class="hljs-string">'/api/data'</span>).then(<span class="hljs-function"><span class="hljs-params">r</span> =&gt;</span> r.json());
<span class="hljs-keyword">const</span> resilientApiCall = retry(apiCall, <span class="hljs-number">3</span>);
<span class="hljs-keyword">const</span> rateLimitedApiCall = rateLimit(apiCall, <span class="hljs-number">5</span>, <span class="hljs-number">60000</span>); <span class="hljs-comment">// 5 calls per minute</span>
</code></pre>
<h2 id="heading-when-to-use-asyncawait">When to Use Async/Await</h2>
<p>Async/Await is preferred in most modern JavaScript applications. It has various advantages over Promises, such as:</p>
<ol>
<li><p><strong>Improved readability</strong>: Code reads like synchronous code, making it easier to understand the flow</p>
</li>
<li><p><strong>Better debugging</strong>: Stack traces are cleaner and easier to follow</p>
</li>
<li><p><strong>Simplified error handling</strong>: Single try/catch block can handle multiple async operations</p>
</li>
<li><p><strong>Reduced nesting</strong>: Eliminates the "pyramid of doom" that can occur with promise chains</p>
</li>
<li><p><strong>Easier testing</strong>: Async functions are easier to test and mock</p>
</li>
<li><p><strong>Better IDE support</strong>: Better autocomplete and type inference in modern editors</p>
</li>
</ol>
<p>Let’s look at some examples that demonstrate when async/await would be a better choice.</p>
<h3 id="heading-1-sequential-operations">1. Sequential Operations</h3>
<p>When you need to perform operations one after another:</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">processUserData</span>(<span class="hljs-params">userId</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUser(userId);
        <span class="hljs-keyword">const</span> preferences = <span class="hljs-keyword">await</span> fetchUserPreferences(user.id);
        <span class="hljs-keyword">const</span> recommendations = <span class="hljs-keyword">await</span> generateRecommendations(user, preferences);

        <span class="hljs-keyword">return</span> {
            user,
            preferences,
            recommendations
        };
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Failed to process user data:'</span>, error);
        <span class="hljs-keyword">throw</span> error;
    }
}
</code></pre>
<p><strong>Why this is better than promises</strong>: With promise chaining, you'd need to nest .then() calls or return values through the chain, making it harder to track data flow.</p>
<h3 id="heading-2-complex-error-handling">2. Complex Error Handling</h3>
<p>Async/await allows you to use familiar try/catch syntax and handle errors at the exact point where they might occur. You can have multiple try/catch blocks for different error scenarios, and the error handling logic is co-located with the code that might throw the error.</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">complexOperation</span>(<span class="hljs-params">data</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-comment">// First level: preprocessing errors</span>
        <span class="hljs-keyword">const</span> processedData = <span class="hljs-keyword">await</span> preprocessData(data);

        <span class="hljs-keyword">try</span> {
            <span class="hljs-comment">// Second level: critical operation errors</span>
            <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> performCriticalOperation(processedData);
            <span class="hljs-keyword">return</span> result;
        } <span class="hljs-keyword">catch</span> (criticalError) {
            <span class="hljs-comment">// Handle critical operation errors specifically</span>
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Critical operation failed:'</span>, criticalError);

            <span class="hljs-comment">// We can make decisions based on the error type</span>
            <span class="hljs-keyword">if</span> (criticalError.code === <span class="hljs-string">'TEMPORARY_FAILURE'</span>) {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Attempting fallback operation...'</span>);
                <span class="hljs-keyword">const</span> fallbackResult = <span class="hljs-keyword">await</span> performFallbackOperation(processedData);
                <span class="hljs-keyword">return</span> fallbackResult;
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-comment">// Re-throw if it's not recoverable</span>
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Critical failure: <span class="hljs-subst">${criticalError.message}</span>`</span>);
            }
        }

    } <span class="hljs-keyword">catch</span> (preprocessError) {
        <span class="hljs-comment">// Handle preprocessing errors differently</span>
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Preprocessing failed:'</span>, preprocessError);

        <span class="hljs-comment">// We can inspect the error and decide how to handle it</span>
        <span class="hljs-keyword">if</span> (preprocessError.code === <span class="hljs-string">'INVALID_DATA'</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Invalid input data provided'</span>);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Unable to process data'</span>);
        }
    }
}
</code></pre>
<p><strong>Explanation of the code:</strong></p>
<ul>
<li><p>The outer try/catch handles preprocessing errors</p>
</li>
<li><p>The inner try/catch specifically handles critical operation errors</p>
</li>
<li><p>Each error handler can make different decisions based on error types</p>
</li>
<li><p>The code clearly shows the error-handling strategy at each level</p>
</li>
<li><p>You can easily add logging, metrics, or recovery logic at each level</p>
</li>
</ul>
<h3 id="heading-3-conditional-asynchronous-logic">3. Conditional Asynchronous Logic</h3>
<p>Async/await makes it natural to use standard control flow (if/else, loops, switch statements) with asynchronous operations. This is much cleaner than trying to implement conditional logic within promise chains.</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">smartUserProcess</span>(<span class="hljs-params">userId</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-comment">// First, get the user data</span>
        <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUser(userId);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Processing user: <span class="hljs-subst">${user.name}</span> (Premium: <span class="hljs-subst">${user.isPremium}</span>)`</span>);

        <span class="hljs-comment">// Make decisions based on the async result</span>
        <span class="hljs-keyword">if</span> (user.isPremium) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User is premium - fetching premium features'</span>);

            <span class="hljs-comment">// Premium users get additional data</span>
            <span class="hljs-keyword">const</span> premiumData = <span class="hljs-keyword">await</span> fetchPremiumFeatures(user.id);

            <span class="hljs-comment">// We can make further decisions based on premium data</span>
            <span class="hljs-keyword">if</span> (premiumData.analyticsEnabled) {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Analytics enabled - generating premium analytics'</span>);
                <span class="hljs-keyword">const</span> analytics = <span class="hljs-keyword">await</span> generatePremiumAnalytics(user, premiumData);
                <span class="hljs-keyword">return</span> { user, premiumData, analytics };
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-keyword">return</span> { user, premiumData };
            }

        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User is basic - fetching basic features'</span>);

            <span class="hljs-comment">// Basic users get different treatment</span>
            <span class="hljs-keyword">const</span> basicData = <span class="hljs-keyword">await</span> fetchBasicFeatures(user.id);

            <span class="hljs-comment">// Check if user qualifies for upgrade prompts</span>
            <span class="hljs-keyword">if</span> (basicData.usageLevel &gt; <span class="hljs-number">0.8</span>) {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User has high usage - checking upgrade eligibility'</span>);
                <span class="hljs-keyword">const</span> upgradeOffer = <span class="hljs-keyword">await</span> checkUpgradeEligibility(user);
                <span class="hljs-keyword">return</span> { user, basicData, upgradeOffer };
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-keyword">return</span> { user, basicData };
            }
        }
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'User processing failed:'</span>, error);

        <span class="hljs-comment">// Even error handling can be conditional</span>
        <span class="hljs-keyword">if</span> (error.code === <span class="hljs-string">'USER_NOT_FOUND'</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'User does not exist'</span>);
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (error.code === <span class="hljs-string">'NETWORK_ERROR'</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network connectivity issue'</span>);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">throw</span> error;
        }
    }
}
</code></pre>
<p><strong>Explanation of the code:</strong></p>
<ul>
<li><p>We await the user fetch and immediately use the result in an if statement</p>
</li>
<li><p>Each branch of the conditional can perform different async operations</p>
</li>
<li><p>We can nest conditions naturally (like checking analyticsEnabled)</p>
</li>
<li><p>Standard control flow works seamlessly with async operations</p>
</li>
<li><p>Error handling can also be conditional based on error types</p>
</li>
<li><p>The code reads like synchronous code but handles async operations correctly</p>
</li>
</ul>
<h2 id="heading-performance-considerations">Performance Considerations</h2>
<p>Understanding the performance implications of different asynchronous patterns is crucial for building efficient JavaScript applications. The main performance consideration is whether your asynchronous operations can run in parallel or must be executed sequentially.</p>
<p>When working with multiple asynchronous operations, you have two main execution patterns: sequential (one after another) and parallel (multiple operations at the same time). The choice between these patterns can significantly impact your application's performance and user experience.</p>
<h3 id="heading-sequential-vs-parallel-execution">Sequential vs Parallel Execution</h3>
<h4 id="heading-sequential-execution-slower-but-sometimes-necessary">Sequential Execution (slower but sometimes necessary):</h4>
<p>Sequential execution means waiting for each operation to complete before starting the next one. This is slower but necessary when operations depend on each other.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// This takes ~3 seconds total (1 + 1 + 1)</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sequentialOperations</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.time(<span class="hljs-string">'Sequential Operations'</span>);

    <span class="hljs-keyword">const</span> result1 = <span class="hljs-keyword">await</span> operation1(); <span class="hljs-comment">// 1 second - must complete first</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Operation 1 completed:'</span>, result1);

    <span class="hljs-keyword">const</span> result2 = <span class="hljs-keyword">await</span> operation2(); <span class="hljs-comment">// 1 second - starts after operation1</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Operation 2 completed:'</span>, result2);

    <span class="hljs-keyword">const</span> result3 = <span class="hljs-keyword">await</span> operation3(); <span class="hljs-comment">// 1 second - starts after operation2</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Operation 3 completed:'</span>, result3);

    <span class="hljs-built_in">console</span>.timeEnd(<span class="hljs-string">'Sequential Operations'</span>);
    <span class="hljs-keyword">return</span> [result1, result2, result3];
}
</code></pre>
<p><strong>Use sequential execution when:</strong></p>
<ul>
<li><p>Each operation depends on the result of the previous one</p>
</li>
<li><p>You need to process results in a specific order</p>
</li>
<li><p>Operations must be rate-limited (for example, API calls with rate limits)</p>
</li>
<li><p>You want to avoid overwhelming external services</p>
</li>
</ul>
<h4 id="heading-parallel-execution-faster-when-possible">Parallel Execution (faster when possible):</h4>
<p>Parallel execution means starting all operations at the same time and waiting for all of them to complete. This is much faster when operations are independent.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// This takes ~1 second total (all operations run simultaneously)</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">parallelOperations</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.time(<span class="hljs-string">'Parallel Operations'</span>);

    <span class="hljs-comment">// Start all operations immediately - they run concurrently</span>
    <span class="hljs-keyword">const</span> promise1 = operation1(); <span class="hljs-comment">// starts immediately</span>
    <span class="hljs-keyword">const</span> promise2 = operation2(); <span class="hljs-comment">// starts immediately  </span>
    <span class="hljs-keyword">const</span> promise3 = operation3(); <span class="hljs-comment">// starts immediately</span>

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'All operations started, waiting for completion...'</span>);

    <span class="hljs-comment">// Wait for all operations to complete</span>
    <span class="hljs-keyword">const</span> [result1, result2, result3] = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all([
        promise1,
        promise2,
        promise3
    ]);

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'All operations completed'</span>);
    <span class="hljs-built_in">console</span>.timeEnd(<span class="hljs-string">'Parallel Operations'</span>);
    <span class="hljs-keyword">return</span> [result1, result2, result3];
}
</code></pre>
<p><strong>Use parallel execution when:</strong></p>
<ul>
<li><p>Operations are independent of each other</p>
</li>
<li><p>You want to minimize total execution time</p>
</li>
<li><p>Dealing with I/O operations (file reads, API calls, database queries)</p>
</li>
<li><p>The order of completion doesn't matter</p>
</li>
</ul>
<h4 id="heading-advanced-example-mixed-approach">Advanced Example - Mixed Approach:</h4>
<p>Sometimes you need a combination of both approaches:</p>
<pre><code class="lang-javascript">javascriptasync <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mixedApproach</span>(<span class="hljs-params">userIds</span>) </span>{
    <span class="hljs-built_in">console</span>.time(<span class="hljs-string">'Mixed Approach'</span>);

    <span class="hljs-comment">// Step 1: Fetch all users in parallel (they're independent)</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Fetching users in parallel...'</span>);
    <span class="hljs-keyword">const</span> users = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all(
        userIds.map(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> fetchUser(id))
    );

    <span class="hljs-comment">// Step 2: Process each user sequentially (to avoid overwhelming the recommendation service)</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Processing users sequentially...'</span>);
    <span class="hljs-keyword">const</span> results = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> user <span class="hljs-keyword">of</span> users) {
        <span class="hljs-keyword">const</span> preferences = <span class="hljs-keyword">await</span> fetchUserPreferences(user.id);
        <span class="hljs-keyword">const</span> recommendations = <span class="hljs-keyword">await</span> generateRecommendations(user, preferences);
        results.push({ user, preferences, recommendations });

        <span class="hljs-comment">// Small delay to be respectful to the API</span>
        <span class="hljs-keyword">await</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>(resolve, <span class="hljs-number">100</span>));
    }

    <span class="hljs-built_in">console</span>.timeEnd(<span class="hljs-string">'Mixed Approach'</span>);
    <span class="hljs-keyword">return</span> results;
}
</code></pre>
<p>Use <code>Promise.all()</code> when operations can run independently and simultaneously.</p>
<h2 id="heading-error-handling-patterns">Error Handling Patterns</h2>
<p>Proper error handling is crucial for building robust applications. Different asynchronous patterns offer different approaches to error handling, each with their own advantages and use cases.</p>
<p>Error handling in asynchronous JavaScript can be challenging because errors can occur at different points in the execution flow. Understanding how to properly catch, handle, and recover from errors in both Promise and async/await patterns is essential for building reliable applications.</p>
<h3 id="heading-promise-error-handling">Promise Error Handling:</h3>
<p>With Promises, errors are handled using the <code>.catch()</code> method. This approach provides fine-grained control over error handling at different points in the chain.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">promiseErrorHandling</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> fetchData()
        .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data fetched successfully'</span>);
            <span class="hljs-keyword">return</span> processData(data);
        })
        .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data processed successfully'</span>);
            <span class="hljs-keyword">return</span> saveResult(result);
        })
        .then(<span class="hljs-function"><span class="hljs-params">savedResult</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Result saved successfully'</span>);
            <span class="hljs-keyword">return</span> savedResult;
        })
        .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 occurred in the chain:'</span>, error);

            <span class="hljs-comment">// Handle different types of errors</span>
            <span class="hljs-keyword">if</span> (error.name === <span class="hljs-string">'NetworkError'</span>) {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Network issue detected, attempting retry...'</span>);
                <span class="hljs-keyword">return</span> retryOperation();
            } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (error.name === <span class="hljs-string">'ValidationError'</span>) {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data validation failed:'</span>, error.message);
                <span class="hljs-keyword">return</span> handleValidationError(error);
            } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (error.name === <span class="hljs-string">'StorageError'</span>) {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Storage operation failed, using fallback'</span>);
                <span class="hljs-keyword">return</span> saveToFallbackStorage(error.data);
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Unknown error type:'</span>, error);
                <span class="hljs-keyword">throw</span> error; <span class="hljs-comment">// Re-throw if we can't handle it</span>
            }
        });
}
</code></pre>
<p><strong>Here’s what’s going on in this code:</strong></p>
<ul>
<li><p>The <code>.catch()</code> method catches any error that occurs in the entire chain</p>
</li>
<li><p>You can inspect the error object to determine the appropriate response</p>
</li>
<li><p>Returning a value from <code>.catch()</code> recovers from the error</p>
</li>
<li><p>Throwing an error or not returning anything propagates the error further</p>
</li>
<li><p>The error handler has access to the original error context</p>
</li>
</ul>
<h3 id="heading-asyncawait-error-handling">Async/Await Error Handling</h3>
<p>With async/await, errors are handled using try/catch blocks, which provide more familiar and flexible error-handling patterns.</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">asyncAwaitErrorHandling</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Starting data processing...'</span>);

        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetchData();
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data fetched successfully'</span>);

        <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> processData(data);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data processed successfully'</span>);

        <span class="hljs-keyword">const</span> savedResult = <span class="hljs-keyword">await</span> saveResult(result);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Result saved successfully'</span>);

        <span class="hljs-keyword">return</span> savedResult;

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

        <span class="hljs-comment">// Handle different types of errors with more complex logic</span>
        <span class="hljs-keyword">if</span> (error.name === <span class="hljs-string">'NetworkError'</span>) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Network issue detected'</span>);

            <span class="hljs-comment">// We can use async operations in error handling</span>
            <span class="hljs-keyword">const</span> retryCount = <span class="hljs-keyword">await</span> getRetryCount();
            <span class="hljs-keyword">if</span> (retryCount &lt; <span class="hljs-number">3</span>) {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Retrying... (attempt <span class="hljs-subst">${retryCount + <span class="hljs-number">1</span>}</span>)`</span>);
                <span class="hljs-keyword">await</span> incrementRetryCount();
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> retryOperation();
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Max retries reached, switching to offline mode'</span>);
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> switchToOfflineMode();
            }

        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (error.name === <span class="hljs-string">'ValidationError'</span>) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data validation failed:'</span>, error.message);

            <span class="hljs-comment">// Handle validation errors with user feedback</span>
            <span class="hljs-keyword">await</span> logValidationError(error);
            <span class="hljs-keyword">return</span> handleValidationError(error);

        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (error.name === <span class="hljs-string">'StorageError'</span>) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Storage operation failed'</span>);

            <span class="hljs-comment">// Try multiple fallback options</span>
            <span class="hljs-keyword">try</span> {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> saveToFallbackStorage(error.data);
            } <span class="hljs-keyword">catch</span> (fallbackError) {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Fallback storage also failed, using cache'</span>);
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> saveToCache(error.data);
            }

        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Unknown error type, logging for analysis'</span>);
            <span class="hljs-keyword">await</span> logErrorForAnalysis(error);
            <span class="hljs-keyword">throw</span> error; <span class="hljs-comment">// Re-throw unknown errors</span>
        }
    }
}
</code></pre>
<p><strong>Here’s what’s going on in the code:</strong></p>
<ul>
<li><p>The try/catch block handles all errors in the async function</p>
</li>
<li><p>You can use await inside catch blocks for error recovery operations</p>
</li>
<li><p>Multiple nested try/catch blocks can handle different scenarios</p>
</li>
<li><p>Error handling code can be as complex as needed, including loops and conditions</p>
</li>
<li><p>The error handling logic is co-located with the code that might throw</p>
</li>
</ul>
<h3 id="heading-advanced-error-pattern-specific-error-handling"><strong>Advanced Error Pattern – Specific Error Handling:</strong></h3>
<pre><code class="lang-javascript">javascriptasync <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">advancedErrorHandling</span>(<span class="hljs-params">userId</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUser(userId);

        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> sensitiveData = <span class="hljs-keyword">await</span> fetchSensitiveData(user.id);
            <span class="hljs-keyword">return</span> { user, sensitiveData };
        } <span class="hljs-keyword">catch</span> (sensitiveError) {
            <span class="hljs-comment">// Handle sensitive data errors specifically</span>
            <span class="hljs-keyword">if</span> (sensitiveError.code === <span class="hljs-string">'PERMISSION_DENIED'</span>) {
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User lacks permission for sensitive data'</span>);
                <span class="hljs-keyword">return</span> { user, <span class="hljs-attr">sensitiveData</span>: <span class="hljs-literal">null</span>, <span class="hljs-attr">reason</span>: <span class="hljs-string">'permission_denied'</span> };
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-comment">// For other sensitive data errors, we still want to return the user</span>
                <span class="hljs-built_in">console</span>.warn(<span class="hljs-string">'Sensitive data unavailable:'</span>, sensitiveError.message);
                <span class="hljs-keyword">return</span> { user, <span class="hljs-attr">sensitiveData</span>: <span class="hljs-literal">null</span>, <span class="hljs-attr">reason</span>: <span class="hljs-string">'data_unavailable'</span> };
            }
        }

    } <span class="hljs-keyword">catch</span> (userError) {
        <span class="hljs-comment">// Handle user fetching errors</span>
        <span class="hljs-keyword">if</span> (userError.code === <span class="hljs-string">'USER_NOT_FOUND'</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`User <span class="hljs-subst">${userId}</span> does not exist`</span>);
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (userError.code === <span class="hljs-string">'NETWORK_ERROR'</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Unable to connect to user service'</span>);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Failed to fetch user: <span class="hljs-subst">${userError.message}</span>`</span>);
        }
    }
}
</code></pre>
<h2 id="heading-best-practices">Best Practices</h2>
<p>Following these best practices will help you write more reliable, maintainable, and performant asynchronous JavaScript code.</p>
<h3 id="heading-always-handle-errors">Always Handle Errors</h3>
<p>One of the most common mistakes in asynchronous JavaScript is forgetting to handle errors. When an async operation fails without proper error handling, it can lead to unhandled promise rejections, application crashes, or silent failures that are difficult to debug.</p>
<p>Don't do this:</p>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// Missing error handling - this is dangerous!</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">badExample</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetchData(); <span class="hljs-comment">// What if this fails?</span>
    <span class="hljs-keyword">const</span> processed = <span class="hljs-keyword">await</span> processData(data); <span class="hljs-comment">// What if this fails?</span>
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> saveData(processed); <span class="hljs-comment">// What if this fails?</span>
}

<span class="hljs-comment">// Usage - user has no idea if something went wrong</span>
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> badExample();
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Could be undefined or cause a crash</span>
</code></pre>
<p><strong>Why this is problematic:</strong></p>
<ul>
<li><p>If <code>fetchData()</code> fails, the entire function crashes</p>
</li>
<li><p>The caller has no way to know what went wrong</p>
</li>
<li><p>In production, this could lead to a poor user experience</p>
</li>
<li><p>Debugging becomes much harder without proper error context</p>
</li>
</ul>
<p>Do this instead:</p>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// Proper error handling with context and recovery</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">goodExample</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Starting data processing...'</span>);

        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetchData();
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data fetched successfully'</span>);

        <span class="hljs-keyword">const</span> processed = <span class="hljs-keyword">await</span> processData(data);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data processed successfully'</span>);

        <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> saveData(processed);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data saved successfully'</span>);

        <span class="hljs-keyword">return</span> result;
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-comment">// Log the error with context</span>
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Data processing failed:'</span>, {
            <span class="hljs-attr">error</span>: error.message,
            <span class="hljs-attr">step</span>: error.step || <span class="hljs-string">'unknown'</span>,
            <span class="hljs-attr">timestamp</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toISOString()
        });

        <span class="hljs-comment">// Re-throw with more context or handle appropriately</span>
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Data processing failed: <span class="hljs-subst">${error.message}</span>`</span>);
    }
}

<span class="hljs-comment">// Usage - caller knows how to handle failures</span>
<span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> goodExample();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Success:'</span>, result);
} <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Failed to process data:'</span>, error.message);
    <span class="hljs-comment">// Handle the error appropriately for your application</span>
    showErrorToUser(<span class="hljs-string">'Data processing failed. Please try again.'</span>);
}
</code></pre>
<p><strong>Why this is better:</strong></p>
<ul>
<li><p>Every async operation is wrapped in try/catch</p>
</li>
<li><p>Errors are logged with useful context</p>
</li>
<li><p>The caller receives meaningful error messages</p>
</li>
<li><p>The application can gracefully handle failures</p>
</li>
</ul>
<h3 id="heading-use-promiseall-for-independent-operations">Use <code>Promise.all()</code> for Independent Operations</h3>
<p>A common performance anti-pattern is making independent async operations run sequentially when they could run in parallel. This unnecessarily increases the total execution time.</p>
<p>Don't do this:</p>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// Sequential when it could be parallel - this is inefficient!</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inefficient</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.time(<span class="hljs-string">'Inefficient Approach'</span>);

    <span class="hljs-comment">// These operations are independent but run one after another</span>
    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUser();        <span class="hljs-comment">// 500ms</span>
    <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> fetchPosts();      <span class="hljs-comment">// 300ms  </span>
    <span class="hljs-keyword">const</span> comments = <span class="hljs-keyword">await</span> fetchComments(); <span class="hljs-comment">// 400ms</span>
    <span class="hljs-comment">// Total time: ~1200ms</span>

    <span class="hljs-built_in">console</span>.timeEnd(<span class="hljs-string">'Inefficient Approach'</span>);
    <span class="hljs-keyword">return</span> { user, posts, comments };
}
</code></pre>
<p><strong>Why this is problematic:</strong></p>
<ul>
<li><p>Each operation waits for the previous one to complete</p>
</li>
<li><p>Total execution time is the sum of all individual times</p>
</li>
<li><p>Network resources are underutilized</p>
</li>
<li><p>Users experience unnecessary delays</p>
</li>
</ul>
<p>This is particularly common when fetching data for a dashboard or page that needs multiple pieces of information. Developers often write the code sequentially without considering that these operations can run simultaneously.</p>
<p>Do this instead:</p>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// Parallel execution - much more efficient!</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">efficient</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.time(<span class="hljs-string">'Efficient Approach'</span>);

    <span class="hljs-comment">// Start all operations simultaneously</span>
    <span class="hljs-keyword">const</span> userPromise = fetchUser();        <span class="hljs-comment">// starts immediately</span>
    <span class="hljs-keyword">const</span> postsPromise = fetchPosts();      <span class="hljs-comment">// starts immediately</span>
    <span class="hljs-keyword">const</span> commentsPromise = fetchComments(); <span class="hljs-comment">// starts immediately</span>

    <span class="hljs-comment">// Wait for all to complete</span>
    <span class="hljs-keyword">const</span> [user, posts, comments] = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all([
        userPromise,
        postsPromise, 
        commentsPromise
    ]);
    <span class="hljs-comment">// Total time: ~500ms (longest individual operation)</span>

    <span class="hljs-built_in">console</span>.timeEnd(<span class="hljs-string">'Efficient Approach'</span>);
    <span class="hljs-keyword">return</span> { user, posts, comments };
}
</code></pre>
<h4 id="heading-advanced-example-with-error-handling">Advanced example with error handling:</h4>
<pre><code class="lang-javascript">javascriptasync <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">efficientWithErrorHandling</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Starting parallel data fetch...'</span>);

        <span class="hljs-comment">// Start all operations and handle individual failures</span>
        <span class="hljs-keyword">const</span> results = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.allSettled([
            fetchUser().catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> ({ <span class="hljs-attr">error</span>: error.message, <span class="hljs-attr">type</span>: <span class="hljs-string">'user'</span> })),
            fetchPosts().catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> ({ <span class="hljs-attr">error</span>: error.message, <span class="hljs-attr">type</span>: <span class="hljs-string">'posts'</span> })),
            fetchComments().catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> ({ <span class="hljs-attr">error</span>: error.message, <span class="hljs-attr">type</span>: <span class="hljs-string">'comments'</span> }))
        ]);

        <span class="hljs-comment">// Process results and handle partial failures</span>
        <span class="hljs-keyword">const</span> [userResult, postsResult, commentsResult] = results;

        <span class="hljs-keyword">return</span> {
            <span class="hljs-attr">user</span>: userResult.status === <span class="hljs-string">'fulfilled'</span> ? userResult.value : <span class="hljs-literal">null</span>,
            <span class="hljs-attr">posts</span>: postsResult.status === <span class="hljs-string">'fulfilled'</span> ? postsResult.value : [],
            <span class="hljs-attr">comments</span>: commentsResult.status === <span class="hljs-string">'fulfilled'</span> ? commentsResult.value : [],
            <span class="hljs-attr">errors</span>: results
                .filter(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.status === <span class="hljs-string">'rejected'</span> || result.value?.error)
                .map(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.reason || result.value?.error)
        };

    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Failed to fetch data:'</span>, error);
        <span class="hljs-keyword">throw</span> error;
    }
}
</code></pre>
<p><strong>Why this is better:</strong></p>
<ul>
<li><p>Operations run in parallel, reducing total execution time</p>
</li>
<li><p>Network and CPU resources are used more efficiently</p>
</li>
<li><p>The application feels more responsive to users</p>
</li>
<li><p>Can handle partial failures gracefully</p>
</li>
</ul>
<h2 id="heading-dont-mix-patterns-unnecessarily">Don't Mix Patterns Unnecessarily</h2>
<p>Mixing Promise chains with async/await in the same function creates inconsistent code that's harder to read, debug, and maintain. It can also lead to subtle bugs and makes the code flow less predictable.</p>
<p>Avoid this:</p>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// Mixing async/await with .then() - this is confusing!</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mixedPattern</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetchData();

    <span class="hljs-comment">// Suddenly switching to Promise chain style</span>
    <span class="hljs-keyword">return</span> processData(data).then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Processing complete'</span>);
        <span class="hljs-keyword">return</span> saveResult(result);
    }).then(<span class="hljs-function"><span class="hljs-params">savedResult</span> =&gt;</span> {
        <span class="hljs-keyword">return</span> savedResult.id;
    }).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);
        <span class="hljs-keyword">throw</span> error;
    });
}
</code></pre>
<p><strong>Why this is problematic:</strong></p>
<ul>
<li><p>Inconsistent error handling patterns (try/catch vs .catch())</p>
</li>
<li><p>Harder to follow the execution flow</p>
</li>
<li><p>Different debugging experiences</p>
</li>
<li><p>More opportunities for bugs</p>
</li>
<li><p>Team members need to understand multiple patterns</p>
</li>
</ul>
<p>This often happens when developers are working with existing Promise-based code and try to gradually introduce async/await without fully converting the function.</p>
<p>Do this instead:</p>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// Consistent async/await - much clearer!</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">consistentPattern</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetchData();
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data fetched'</span>);

        <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> processData(data);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Processing complete'</span>);

        <span class="hljs-keyword">const</span> savedResult = <span class="hljs-keyword">await</span> saveResult(result);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Result saved'</span>);

        <span class="hljs-keyword">return</span> savedResult.id;
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error in async function:'</span>, error);
        <span class="hljs-keyword">throw</span> error;
    }
}
</code></pre>
<p><strong>Alternative consistent Promise approach:</strong></p>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// If you prefer Promises, be consistent with that too</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">consistentPromisePattern</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> fetchData()
        .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Data fetched'</span>);
            <span class="hljs-keyword">return</span> processData(data);
        })
        .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Processing complete'</span>);
            <span class="hljs-keyword">return</span> saveResult(result);
        })
        .then(<span class="hljs-function"><span class="hljs-params">savedResult</span> =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Result saved'</span>);
            <span class="hljs-keyword">return</span> savedResult.id;
        })
        .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);
            <span class="hljs-keyword">throw</span> error;
        });
}
</code></pre>
<h3 id="heading-use-descriptive-variable-names-in-async-functions"><strong>Use Descriptive Variable Names in Async Functions</strong></h3>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// Poor naming</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">process</span>(<span class="hljs-params">id</span>) </span>{
    <span class="hljs-keyword">const</span> d = <span class="hljs-keyword">await</span> fetch(id);
    <span class="hljs-keyword">const</span> r = <span class="hljs-keyword">await</span> transform(d);
    <span class="hljs-keyword">return</span> r;
}

<span class="hljs-comment">// Better naming</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processUserProfile</span>(<span class="hljs-params">userId</span>) </span>{
    <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> fetchUserData(userId);
    <span class="hljs-keyword">const</span> transformedProfile = <span class="hljs-keyword">await</span> transformUserData(userData);
    <span class="hljs-keyword">return</span> transformedProfile;
}
</code></pre>
<h3 id="heading-handle-timeouts-for-long-running-operations"><strong>Handle Timeouts for Long-Running Operations</strong></h3>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// Add timeout wrapper for reliability</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withTimeout</span>(<span class="hljs-params">promise, timeoutMs</span>) </span>{
    <span class="hljs-keyword">const</span> timeout = <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">'Operation timed out'</span>)), timeoutMs);
    });

    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.race([promise, timeout]);
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reliableDataFetch</span>(<span class="hljs-params">userId</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-comment">// Timeout after 5 seconds</span>
        <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> withTimeout(fetchUserData(userId), <span class="hljs-number">5000</span>);
        <span class="hljs-keyword">return</span> userData;
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-keyword">if</span> (error.message === <span class="hljs-string">'Operation timed out'</span>) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Request timed out, using cached data'</span>);
            <span class="hljs-keyword">return</span> getCachedUserData(userId);
        }
        <span class="hljs-keyword">throw</span> error;
    }
}
</code></pre>
<h2 id="heading-making-the-right-choice">Making the Right Choice</h2>
<p>Here's a decision framework to help you choose:</p>
<h3 id="heading-choose-promises-when">Choose Promises When:</h3>
<ul>
<li><p>Working with libraries that return Promises</p>
</li>
<li><p>Writing functional programming style code</p>
</li>
<li><p>Creating utility functions that other code will chain</p>
</li>
<li><p>You need fine-grained control over Promise behavior</p>
</li>
<li><p>Working with existing Promise-based codebases</p>
</li>
</ul>
<h3 id="heading-choose-asyncawait-when">Choose Async/Await When:</h3>
<ul>
<li><p>Writing new application code</p>
</li>
<li><p>You need sequential operations with a clear flow</p>
</li>
<li><p>Complex error handling is required</p>
</li>
<li><p>Working with conditional asynchronous logic</p>
</li>
<li><p>Code readability is a priority</p>
</li>
<li><p>You're building modern JavaScript applications</p>
</li>
</ul>
<h3 id="heading-consider-both-when">Consider Both When:</h3>
<ul>
<li><p>Using <code>Promise.all()</code>, <code>Promise.race()</code>, or <code>Promise.allSettled()</code></p>
</li>
<li><p>Building complex asynchronous flows</p>
</li>
<li><p>You need both the power of Promises and the readability of Async/Await</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Both Promises and Async/Await are powerful tools for handling asynchronous operations in JavaScript. Promises provide flexibility and fine-grained control, while Async/Await offers cleaner, more readable code that's easier to debug and maintain.</p>
<p>In modern JavaScript development, Async/Await is generally preferred for application code due to its readability and ease of use. However, understanding Promises is still crucial since Async/Await is built on top of them, and many libraries and APIs still use Promises directly.</p>
<p>The key is to understand both approaches and choose the one that best fits your specific use case, team preferences, and project requirements. Remember that you can always mix both approaches when it makes sense – use Async/Await for your main application logic and Promises for utility functions and library integrations.</p>
<p>By mastering both techniques very well, you will be well-equipped to handle any asynchronous programming challenge in JavaScript.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Asynchronous Programming Works in Rust – Futures and Async/Await Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ If you're familiar with languages like JavaScript and Python, you may have heard about asynchronous programming. And perhaps you're wondering how it works in Rust. In this article, I'll give you a simple overview of how asynchronous programming works... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-asynchronous-programming-works-in-rust/</link>
                <guid isPermaLink="false">66be1c3ab712ab343b0b9150</guid>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oduah Chigozie ]]>
                </dc:creator>
                <pubDate>Thu, 15 Aug 2024 15:18:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723746256888/b046d857-161c-41be-96d0-1c05b1e448b8.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're familiar with languages like JavaScript and Python, you may have heard about asynchronous programming. And perhaps you're wondering how it works in Rust.</p>
<p>In this article, I'll give you a simple overview of how asynchronous programming works in Rust. You'll learn about futures as well as <code>async</code>/<code>.await</code>.</p>
<p>This article isn't a beginner's guide to Rust or asynchronous programming, so you'll need to have some experience with programming in Rust and familiarity with asynchronous programming to get the most out of this guide.</p>
<p>With that said, let's begin!</p>
<h2 id="heading-when-should-you-use-asynchronous-programming">When Should You Use Asynchronous Programming?</h2>
<p>Asynchronous tasks work like a more integrated version of threads. You can use them in a lot of the same scenarios where you can use multiple threads. The benefits async programming provides over multiple threads is that multi-threaded applications have a larger overhead to work on multiple tasks compared to asynchronous applications.</p>
<p>But this doesn’t make asynchronous applications better than multithreaded applications. Multi-threaded programs can run multiple computing-intensive tasks simultaneously – and multiple times faster than if you ran all the tasks in a single thread.</p>
<p>With asynchronous coding, trying to run multiple computing-intensive applications simultaneously will be much slower than just running every task on a single thread.</p>
<p>Asynchronous programming is very good for building applications that make many network requests or many IO operations like file reading and writing.</p>
<p>I can’t cover every case when you’ll want to use asynchronous techniques. But I can say that it’s most beneficial for tasks that have a lot of idle time (for example, waiting for a server to respond to a network request).</p>
<p>During the idle time of an asynchronous task, instead of blocking the thread, the event handler works on other tasks in the program until the asynchronous task is ready to make progress.</p>
<h2 id="heading-overview-of-asynchronous-rust-futures">Overview of Asynchronous Rust – Futures</h2>
<p>The basics of asynchronous Rust are Futures. Futures are similar to promises in JavaScript. They are Rust's way of saying "hey, I'm going to give you the result later, but just hold on to this (the future instance) to keep track of if the result is ready."</p>
<p>Futures are traits, with a <code>poll</code> state that is either <code>Poll::Pending</code> to signify that the future is in the process of executing its task, or <code>Poll::Ready</code> to signify that the future is done with its task.</p>
<p>Futures are lazy. They run when you <code>.await</code> them (we'll look into how to <code>.await</code> them in the next section). <code>.await</code>ing a future pauses the execution of an asynchronous thread, and begins running its task. At this point the result of the <code>poll</code> method is <code>Poll::Pending</code>. When the future is done with its task, <code>poll</code>'s state will become <code>Poll::Ready</code>, and the future will allow it's thread to proceed.</p>
<p>If you want to get more into the technical details about Futures, you can check out <a target="_blank" href="https://rust-lang.github.io/async-book/02_execution/01_chapter.html">the documentation</a>.</p>
<h2 id="heading-asyncawait-in-rust">async/.await in Rust</h2>
<p><code>async</code> and <code>.await</code> are the primary ways you'll be working with asynchronous code in Rust. <code>async</code> is a keyword for declaring asynchronous functions. Within those functions, the <code>.await</code> keyword pauses its execution until the result of the future is ready.</p>
<p>Let's take a look at an example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add</span></span>(a: <span class="hljs-built_in">u8</span>, b: <span class="hljs-built_in">u8</span>) -&gt; <span class="hljs-built_in">u8</span> {
    a + b
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">secondFunc</span></span>() -&gt; <span class="hljs-built_in">u8</span> {
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">let</span> result = add(a, b).<span class="hljs-keyword">await</span>;
    <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>Any asynchronous function declared with <code>async fn</code> wraps its return value in a future. On the third line of <code>secondFunc</code>, we <code>.await</code> the future from <code>add(a, b)</code> to get its result before proceeding to return it.</p>
<h2 id="heading-how-to-work-with-asynchronous-operations-in-main">How to Work with Asynchronous Operations in <code>main</code></h2>
<p>Rust doesn’t allow you to <code>async fn</code> main functions. Running asynchronous operations from a non-asynchronous function may lead to some operations not fully concluding before the main thread is exited.</p>
<p>In this section, we’ll look at two ways solve this issue. The two ways to do this are with <code>futures</code> and <code>tokio</code>. Let's look at both.</p>
<h3 id="heading-tokio"><code>tokio</code></h3>
<p><code>tokio</code> is a platform that provides tools and APIs for performing asynchronous applications. <code>tokio</code> also allows you to easily declare an asynchronous main function, which will help with the issue I described earlier.</p>
<p>To install <code>tokio</code> in your project, add this line to its <code>Cargo.toml</code>:</p>
<pre><code class="lang-ini"><span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">tokio</span> = { version = <span class="hljs-string">"1"</span>, features = [<span class="hljs-string">"full"</span>] }
</code></pre>
<p>After adding the line, you can write your <code>main</code> functions like this:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add</span></span>(a: <span class="hljs-built_in">u8</span>, b: <span class="hljs-built_in">u8</span>) -&gt; <span class="hljs-built_in">u8</span> {
    a + b
}

<span class="hljs-meta">#[tokio::main]</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">let</span> result = add(a, b).<span class="hljs-keyword">await</span>;
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{result}"</span>);
}
</code></pre>
<h3 id="heading-the-futures-library">The <code>futures</code> library</h3>
<p><code>futures</code> is a library that provides methods for working with asynchronous Rust. For our use case, <code>futures</code> provides <code>futures::executor::block_on()</code>. This method works similar to <code>.await</code> in asynchronous functions. It blocks the main thread, until the result of future is ready. <code>futures::executor::block_on()</code> also returns the result of the completed future.</p>
<p>To install <code>futures</code> in your project, add this line to its <code>Cargo.toml</code>:</p>
<pre><code class="lang-ini"><span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">futures</span> = <span class="hljs-string">"0.3"</span>
</code></pre>
<p>After installing the library, you can do something like this:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> futures::executor::block_on;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add</span></span>(a: <span class="hljs-built_in">u8</span>, b: <span class="hljs-built_in">u8</span>) -&gt; <span class="hljs-built_in">u8</span> {
    a + b
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">let</span> result = block_on(add(a, b));
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{result}"</span>); 
}
</code></pre>
<p>First, we import the <code>block_on</code> method on the first line and use the method to block the main thread until the result of the <code>add(a, b)</code> function was ready. We also didn’t have to make the <code>main</code> function asynchronous like we did with <code>tokio</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Asynchronous programming allows you to run operations in parallel and with less overhead and complexity compared to traditional multi-threading. In Rust, it allows you to build I/O and network applications more efficiently.</p>
<p>While this article should help you become familiar with the basics asynchronous programming in Rust, it’s still just an overview. There are some cases where you'll need to use other constructs in Rust like Pinning, Arcs, and so on.</p>
<p>If you have any questions or thoughts, feel free to reach out to me. Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <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[ How to Use Async/Await in JavaScript – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Hello friends! In this article, I'm going to show you how to use the “async/await” special syntax when handling JavaScript Promises. If you don't know or need a refresher on JavaScript promises, you can read my previous article: How JavaScript Promis... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-async-await/</link>
                <guid isPermaLink="false">66bd91766d46d5e73b73e91d</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Fri, 15 Dec 2023 15:33:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/js-async-await.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hello friends! In this article, I'm going to show you how to use the “async/await” special syntax when handling JavaScript Promises.</p>
<p>If you don't know or need a refresher on JavaScript promises, you can read my previous article: <a target="_blank" href="https://www.freecodecamp.org/news/javascript-promise-object-explained/">How JavaScript Promises Work – Tutorial for Beginners</a>.</p>
<p>You'll need to understand JavaScript promises well before learning the async/await syntax.</p>
<h2 id="heading-how-asyncawait-works">How async/await Works</h2>
<p>The async/await syntax is a special syntax created to help you work with promise objects. It makes your code cleaner and clearer.</p>
<p>When handling a <code>Promise</code>, you need to chain the call to the function or variable that returns a <code>Promise</code> using <code>then/catch</code> methods.</p>
<p>When you have many promises, you will also need lots of <code>then</code> method chains. For example, here's how you might retrieve data using the <code>fetch()</code> function:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</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">json</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(json))
  .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>In the code above, the <code>fetch()</code> function returns a <code>Promise</code>, which we handle using the <code>then()</code> method. Inside the first <code>then()</code> method, we accept the <code>response</code> from the request and convert it into an object using the <code>json()</code> method.</p>
<p>In the second <code>then()</code> method, we receive the returned <code>json</code> data from the call to the <code>json()</code> method, then log that data to the console.</p>
<p>We also add the <code>catch()</code> method to handle any error that might happen when running the request.</p>
<p>The code is really not hard to understand, but we can make it even prettier by removing the <code>.then()</code> and <code>.catch()</code> chains, which also removes the callback functions.</p>
<h3 id="heading-the-await-keyword">The Await Keyword</h3>
<p>The <code>await</code> keyword basically makes JavaScript wait until the <code>Promise</code> object is resolved or rejected. Instead of having to use the callback pattern inside the <code>then()</code> method, you can assign the fulfilled promise into a variable like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
<span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
<span class="hljs-built_in">console</span>.log(json)
</code></pre>
<p>The <code>await</code> keyword is placed before the call to a function or variable that returns a promise. It makes JavaScript wait for the promise object to settle before running the code in the next line.</p>
<p>Now if you run the code above, you might get an error like this:</p>
<pre><code class="lang-txt">SyntaxError: await is only valid in async functions and the top level bodies of modules
</code></pre>
<p>This error occurs because the <code>await</code> keyword must be used inside an asynchronous function or a module.</p>
<h3 id="heading-the-async-keyword">The Async Keyword</h3>
<p>To create an asynchronous function, you need to add the <code>async</code> keyword before your function name. Take a look at line 1 in the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runProcess</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/todos/1'</span>);
  <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
  <span class="hljs-built_in">console</span>.log(json)
}

runProcess();
</code></pre>
<p>Here, we created an asynchronous function called <code>runProcess()</code> and put the code that uses the <code>await</code> keyword inside it. We can then run the asynchronous function by calling it, just like a regular function.</p>
<h2 id="heading-how-to-handle-errors-in-asyncawait">How to Handle Errors in Async/Await</h2>
<p>To handle an error that might occur from the async/await syntax, you can use the try/catch block to catch any rejection from your promise.</p>
<p>See the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runProcess</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://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(json);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
}

runProcess();
</code></pre>
<p>The try/catch block, put inside the <code>runProcess()</code> function, will handle the rejection that comes from the promise objects.</p>
<p>Now we have a complete async/await version of the standard Promise code we created earlier. Here's a comparison between the two:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/PROMISE---ASYNC.png" alt="Image" width="600" height="400" loading="lazy">
<em>Promise vs Async/Await Code Comparison</em></p>
<p>In the async/await version, the result of the promise is directly assigned to a variable. In the standard promise version, the result of the promise is passed as an argument to the <code>.then()</code> method. </p>
<p>Most developers prefer the async/await version as it looks more straightforward.</p>
<h2 id="heading-how-to-use-asyncawait-in-iife-and-arrow-functions">How to Use Async/Await in IIFE and Arrow Functions</h2>
<p>An Immediately Invoked Function Expression (IIFE) is a technique used to execute a function immediately as soon as you define it.</p>
<p>Unlike regular functions and variables, IIFEs will be removed from the running process once they are executed.</p>
<p>Aside from the standard function, you can also make an asynchronous IIFE. This is useful when you need to run the asynchronous function only once:</p>
<pre><code class="lang-js">(<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> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(json);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
})();
</code></pre>
<p>You can also use the arrow syntax when creating an asynchronous function as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> runProcess = <span class="hljs-keyword">async</span> () =&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://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(json);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
};

runProcess();
</code></pre>
<p>Feel free to use the syntax you want in your code.</p>
<h2 id="heading-why-use-the-asyncawait-syntax">Why Use the async/await Syntax?</h2>
<p>The async/await syntax enables you to handle promises without using <code>.then()</code> and <code>.catch()</code> method chaining, which also removes the need for nested callbacks.</p>
<p>This benefit is significant when you have a complex process after the promise is settled. </p>
<p>Going back to our example above, suppose you have a conditional statement inside the <code>.then()</code> method as follows:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</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">json</span> =&gt;</span> {
    <span class="hljs-keyword">if</span> (json.userId == <span class="hljs-number">1</span>) {
      json.completed == <span class="hljs-literal">false</span>;
    } <span class="hljs-keyword">else</span> {
      json.completed == <span class="hljs-literal">true</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>Here, you can see that the callback function that accepts the <code>json</code> data has an if/else block inside it. </p>
<p>This code is hard to reason with and modify when compared to the async/await version as follows:</p>
<pre><code class="lang-js">(<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> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-keyword">if</span> (json.userId == <span class="hljs-number">1</span>) {
      json.completed == <span class="hljs-literal">false</span>;
    } <span class="hljs-keyword">else</span> {
      json.completed == <span class="hljs-literal">true</span>;
    }
    <span class="hljs-built_in">console</span>.log(json);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
})();
</code></pre>
<p>By using the async/await syntax, you reduce the need for method chaining and nested callbacks. This impact the readability of your code, especially when you have nested code like if/else and a for loop block.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now you've learned how the async/await syntax works. The syntax makes working with promises much easier by removing the need for <code>.then()</code> and <code>.catch()</code> method chaining, which also removes the need for nested callbacks.</p>
<p>Even though the <code>await</code> keyword can only be used inside an <code>async</code> function, you can use an IIFE to invoke the async function only once.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous JavaScript – Callbacks, Promises, and Async/Await Explained ]]>
                </title>
                <description>
                    <![CDATA[ If you've been learning JavaScript for a while now, then you've probably heard the term "asynchronous" before. This is because JavaScript is an asynchronous language...but what does that really mean? In this article, I hope to show you that the conce... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-javascript-explained/</link>
                <guid isPermaLink="false">66d460893a8352b6c5a2aac5</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Njong Emy ]]>
                </dc:creator>
                <pubDate>Mon, 20 Jun 2022 20:10:50 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727436410214/26117e35-6f63-4788-9b97-3aa225527213.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've been learning JavaScript for a while now, then you've probably heard the term "asynchronous" before.</p>
<p>This is because JavaScript is an asynchronous language...but what does that really mean? In this article, I hope to show you that the concept is not as difficult as it sounds.</p>
<h1 id="heading-synchronous-vs-asynchronous">Synchronous vs Asynchronous</h1>
<p>Before we hop into the real deal, let's look at these two words – synchronous and asynchronous.</p>
<p>By default, JavaScript is a synchronous, single threaded programming language. This means that instructions can only run one after another, and not in parallel. Consider the little code snippet below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> sum = a + b;
<span class="hljs-built_in">console</span>.log(sum);
</code></pre>
<p>The above code is pretty simple – it sums two numbers and then logs the sum to the browser console. The interpreter executes these instructions one after another in that order until it is done.</p>
<p>But this method comes along with disadvantages. Say we wanted to fetch some large amount of data from a database and then display it on our interface. When the interpreter reaches the instruction that fetches this data, the rest of the code is blocked from executing until the data has been fetched and returned.</p>
<p>Now you might say that the data to be fetched isn't that large and it won't take any noticeable time. Imagine that you have to fetch data at multiple different points. This delay compounded doesn't sound like something users would want to come across.</p>
<p>Luckily for us, the problems with synchronous JavaScript were addressed by introducing asynchronous JavaScript.</p>
<p>Think of asynchronous code as code that can start now, and finish its execution later. When JavaScript is running asynchronously, the instructions are not necessarily executed one after the other as we saw before.</p>
<p>In order to properly implement this asynchronous behavior, there are a few different solutions developers has used over the years. Each solution improves upon the previous one, which makes the code more optimized and easier to understand in case it gets complex.</p>
<p>To further understand the asynchronous nature of JavaScript, we will go through callback functions, promises, and async and await.</p>
<h1 id="heading-what-are-callbacks-in-javascript">What are Callbacks in JavaScript?</h1>
<p>A callback is a function that is passed inside another function, and then called in that function to perform a task.</p>
<p>Confusing? Let's break it down by practically implementing it.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fired first'</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fired 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">'fired third'</span>);
},<span class="hljs-number">2000</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fired last'</span>);
</code></pre>
<p>The snippet above is a small program that logs stuff to the console. But there is something new here. The interpreter will execute the first instruction, then the second, but it will skip over the third and execute the last.</p>
<p>The <code>setTimeout</code> is a JavaScript function that takes two parameters. The first parameter is another function, and the second is the time after which that function should be executed in milliseconds. Now you see the definition of callbacks coming into play.</p>
<p>The function inside <code>setTimeout</code> in this case is required to run after two seconds (2000 milliseconds). Imagine it being carried off to be executed in some separate part of the browser, while the other instructions continue executing. After two seconds, the results of the function are then returned.</p>
<p>That is why if we run the above snippet in our program, we will get this:</p>
<pre><code class="lang-javascript">fired first
fired second
fired last
fired third
</code></pre>
<p>You see that the last instruction is logged before the function in the <code>setTimeout</code> returns its result. Say we used this method to fetch data from a database. While the user is waiting for the database call to return results, the flow in execution will not be interrupted.</p>
<p>This method was very efficient, but only to a certain point. Sometimes, developers have to make multiple calls to different sources in their code. In order to make these calls, callbacks are being nested until they become very hard to read or maintain. This is referred to as <strong>Callback Hell</strong></p>
<p>To fix this problem, promises were introduced.</p>
<h1 id="heading-what-are-promises-in-javascript">What are Promises in JavaScript?</h1>
<p>We hear people make promises all the time. That cousin of yours who promised to send you free money, a kid promising to not touch the cookie jar again without permission...but promises in JavaScript are slightly different.</p>
<p>A promise, in our context, is something which will take some time to do. There are two possible outcomes of a promise:</p>
<ul>
<li><p>We either run and resolve the promise, or</p>
</li>
<li><p>Some error occurs along the line and the promise is rejected</p>
</li>
</ul>
<p>Promises came along to solve the problems of callback functions. A promise takes in two functions as parameters. That is, <code>resolve</code> and <code>reject</code>. Remember that resolve is success, and reject is for when an error occurs.</p>
<p>Let's take a look at promises at work:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getData = <span class="hljs-function">(<span class="hljs-params">dataEndpoint</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-comment">//some request to the endpoint;</span>

     <span class="hljs-keyword">if</span>(request is successful){
       <span class="hljs-comment">//do something;</span>
       resolve();
     }
     <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(there is an error){
       reject();
     }

   });
};
</code></pre>
<p>The code above is a promise, enclosed by a request to some endpoint. The promise takes in <code>resolve</code> and <code>reject</code> like I mentioned before.</p>
<p>After making a call to the endpoint for example, if the request is successful, we would resolve the promise and go on to do whatever we want with the response. But if there is an error, the promise will get rejected.</p>
<p>Promises are a neat way to fix problems brought about by callback hell, in a method known as <strong>promise chaining</strong>. You can use this method to sequentially get data from multiple endpoints, but with less code and easier methods.</p>
<p>But there is an even better way! You might be familiar with the following method, as it's a preferred way of handling data and API calls in JavaScript.</p>
<h1 id="heading-what-is-async-and-await-in-javascript">What is Async and Await in JavaScript?</h1>
<p>The thing is, chaining promises together just like callbacks can get pretty bulky and confusing. That's why Async and Await was brought about.</p>
<p>To define an async function, you do this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> asyncFunc = <span class="hljs-keyword">async</span>() =&gt; {

}
</code></pre>
<p>Note that calling an async function will always return a Promise. Take a look at this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> test = asyncFunc();
<span class="hljs-built_in">console</span>.log(test);
</code></pre>
<p>Running the above in the browser console, we see that the <code>asyncFunc</code> returns a promise.</p>
<p>Let's really break down some code now. Consider the little snippet below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> asyncFunc = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(resource);
       <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
}
</code></pre>
<p>The <code>async</code> keyword is what we use to define async functions as I mentioned above. But how about <code>await</code> ? Well, it stalls JavaScript from assigning <code>fetch</code> to the response variable until the promise has been resolved. Once the promise has been resolved, the results from the fetch method can now be assigned to the response variable.</p>
<p>The same thing happens on line 3. The <code>.json</code> method returns a promise, and we can use <code>await</code> still to delay the assigning until the promise is resolved.</p>
<h1 id="heading-to-block-code-or-not-to-block-code">To Block Code or Not to Block Code</h1>
<p>When I say 'stalling', you must think that implementing Async and Await somehow blocks code execution. Because what if our request takes too long, right?</p>
<p>Fact is, it doesn't. Code that is inside the async function is blocking, but that doesn't affect program execution in any way. The execution of our code is just as asynchronous as ever. To show this,</p>
<pre><code class="lang-markdown">const asyncFunc = async () =&gt; {
<span class="hljs-code">    const response = await fetch(resource);
       const data = await response.json();
}
</span>
console.log(1);
cosole.log(2);

asyncFunc().then(data =&gt; console.log(data));

console.log(3);
console.log(4);
</code></pre>
<p>In our browser console, the output of the above would look something like this:</p>
<pre><code class="lang-markdown">1
2
3
4
data returned by asyncFunc
</code></pre>
<p>You see that as we called <code>asyncFunc</code>, our code continued running until it was time for the function to return results.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>This article does not treat these concepts in great depth, but I hope it shows you what asynchronous JavaScript entails and a few things to look out for.</p>
<p>It is a very essential part of JavaScript, and this article only scratches the surface. Nonetheless, I hope this article helped to break down these concepts.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Async and Await in JavaScript Explained by Making Pizza ]]>
                </title>
                <description>
                    <![CDATA[ By Dave Gray Async and await might sound complicated...but they're as easy as pizza pie once you dive in. We all use async and await in our daily routines. What is an async task? An async task lets you complete other tasks while the async task is sti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/async-await-javascript-tutorial-explained-by-making-pizza/</link>
                <guid isPermaLink="false">66d45e01a3a4f04fb2dd2e37</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 30 Aug 2021 20:20:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/carissa-gan-_0JpjeqtSyg-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dave Gray</p>
<p>Async and await might sound complicated...but they're as easy as pizza pie once you dive in.</p>
<p>We all use async and await in our daily routines.</p>
<h2 id="heading-what-is-an-async-task">What is an async task?</h2>
<p>An async task lets you complete other tasks while the async task is still working towards completion. </p>
<h3 id="heading-here-are-some-day-to-day-async-task-examples">Here are some day-to-day async task examples</h3>
<h4 id="heading-example-1">Example 1:</h4>
<p>You order food at a drive-thru which starts your food request (an async task). </p>
<p>You pull forward in the drive-thru line (the next task), while your food is prepared. </p>
<p>You did not have to wait for your food to be ready before you could pull forward.</p>
<p>You are awaiting your food and your request is fulfilled at the pick-up window.</p>
<h4 id="heading-example-2">Example 2:</h4>
<p>You mop the floor in your kitchen. </p>
<p>While you wait for your kitchen floor to dry, you vacuum the carpet in your bedroom. </p>
<p>The original task was to clean your kitchen floor, and the task is complete when the floor is dry. </p>
<p>Standing around waiting for the floor to dry is not too productive, so you vacuumed the bedroom floor while the kitchen floor dried.</p>
<p><em>This is how Javascript handles async functions, too.</em></p>
<h3 id="heading-example-of-asyncawait-bake-a-frozen-pizza">Example of Async/Await – Bake a Frozen Pizza</h3>
<p>You decide to bake a pizza in your oven, and your first step is to preheat the oven. </p>
<p>So you set the desired temperature and begin to preheat the oven. </p>
<p>While the oven is preheating, you get the frozen pizza out of the freezer, open the box, and put it on a pizza pan. </p>
<p>You've got time left! </p>
<p>Maybe grab a beverage and watch some television while you wait for the oven to beep when it is ready.</p>
<p>Below is some code to simulate this example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// This async function simulates the oven response</span>
<span class="hljs-keyword">const</span> ovenReady = <span class="hljs-keyword">async</span> () =&gt; {
  <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">() =&gt;</span> {
    resolve(<span class="hljs-string">'Beep! Oven preheated!'</span>)
  }, <span class="hljs-number">3000</span>));
}

<span class="hljs-comment">// Define preheatOven async function</span>
<span class="hljs-keyword">const</span> preheatOven = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Preheating oven.'</span>);
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> ovenReady();
  <span class="hljs-built_in">console</span>.log(response);
}

<span class="hljs-comment">// Define the other functions</span>
<span class="hljs-keyword">const</span> getFrozenPizza = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Getting pizza.'</span>);
<span class="hljs-keyword">const</span> openFrozenPizza = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Opening pizza.'</span>);
<span class="hljs-keyword">const</span> getPizzaPan = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Getting pan.'</span>);
<span class="hljs-keyword">const</span> placeFrozenPizzaOnPan = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Putting pizza on pan.'</span>);
<span class="hljs-keyword">const</span> grabABeverage = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Grabbing a beverage.'</span>);
<span class="hljs-keyword">const</span> watchTV = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Watching television.'</span>);

<span class="hljs-comment">// Now call the functions</span>
preheatOven();
getFrozenPizza();
openFrozenPizza();
getPizzaPan();
placeFrozenPizzaOnPan();
grabABeverage();
watchTV();

<span class="hljs-comment">// Output sequence in console:</span>
Preheating oven.
Getting pizza.
Opening pizza.
Getting pan.
Putting pizza on pan.
Grabbing a beverage.
Watching television.
Beep! Oven preheated!

The process above is exactly what <span class="hljs-keyword">async</span> and <span class="hljs-keyword">await</span> is all about. 

While we <span class="hljs-string">`await`</span> <span class="hljs-keyword">for</span> the asynchronous <span class="hljs-string">`preheatOven`</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">to</span> <span class="hljs-title">complete</span>, <span class="hljs-title">we</span> <span class="hljs-title">can</span> <span class="hljs-title">perform</span> <span class="hljs-title">synchronous</span> <span class="hljs-title">tasks</span> <span class="hljs-title">like</span> `<span class="hljs-title">getFrozenPizza</span>`, `<span class="hljs-title">openFrozenPizza</span>`, `<span class="hljs-title">getPizzaPan</span>`, `<span class="hljs-title">placeFrozenPizzaOnPan</span>`, `<span class="hljs-title">grabABeverage</span>` <span class="hljs-title">and</span> <span class="hljs-title">even</span> `<span class="hljs-title">watchTV</span>`.

### <span class="hljs-title">We</span> <span class="hljs-title">perform</span> <span class="hljs-title">asynchronous</span> <span class="hljs-title">tasks</span> <span class="hljs-title">like</span> <span class="hljs-title">this</span> <span class="hljs-title">all</span> <span class="hljs-title">the</span> <span class="hljs-title">time</span>

<span class="hljs-title">And</span> <span class="hljs-title">that</span>'<span class="hljs-title">s</span> <span class="hljs-title">how</span> `<span class="hljs-title">async</span>` <span class="hljs-title">Javascript</span> <span class="hljs-title">works</span>, <span class="hljs-title">too</span>.

<span class="hljs-title">Notice</span> <span class="hljs-title">that</span> <span class="hljs-title">when</span> <span class="hljs-title">we</span> `<span class="hljs-title">await</span>`<span class="hljs-title">a</span> <span class="hljs-title">response</span> <span class="hljs-title">from</span> <span class="hljs-title">an</span> `<span class="hljs-title">async</span>` <span class="hljs-title">function</span>, <span class="hljs-title">it</span> <span class="hljs-title">needs</span> <span class="hljs-title">to</span> <span class="hljs-title">be</span> <span class="hljs-title">called</span> <span class="hljs-title">within</span> <span class="hljs-title">another</span> `<span class="hljs-title">async</span>` <span class="hljs-title">function</span>. <span class="hljs-title">That</span>'<span class="hljs-title">s</span> <span class="hljs-title">what</span> <span class="hljs-title">we</span> <span class="hljs-title">see</span> <span class="hljs-title">above</span> <span class="hljs-title">when</span> `<span class="hljs-title">ovenReady</span>` <span class="hljs-title">is</span> <span class="hljs-title">called</span> <span class="hljs-title">inside</span> <span class="hljs-title">of</span> `<span class="hljs-title">preheatOven</span>`.

### <span class="hljs-title">Two</span> <span class="hljs-title">key</span> <span class="hljs-title">points</span> <span class="hljs-title">to</span> <span class="hljs-title">remember</span>:

1. <span class="hljs-title">Javascript</span> <span class="hljs-title">will</span> <span class="hljs-title">NOT</span> <span class="hljs-title">wait</span> <span class="hljs-title">for</span> <span class="hljs-title">an</span> `<span class="hljs-title">async</span>` <span class="hljs-title">function</span> <span class="hljs-title">like</span> `<span class="hljs-title">preheatOven</span>` <span class="hljs-title">to</span> <span class="hljs-title">complete</span> <span class="hljs-title">before</span> <span class="hljs-title">it</span> <span class="hljs-title">moves</span> <span class="hljs-title">on</span> <span class="hljs-title">to</span> <span class="hljs-title">the</span> <span class="hljs-title">tasks</span> <span class="hljs-title">that</span> <span class="hljs-title">follow</span> <span class="hljs-title">like</span> `<span class="hljs-title">getFrozenPizza</span>` <span class="hljs-title">and</span> `<span class="hljs-title">openFrozenPizza</span>`. 
2. <span class="hljs-title">Javascript</span> <span class="hljs-title">will</span> `<span class="hljs-title">await</span>` <span class="hljs-title">for</span> <span class="hljs-title">an</span> `<span class="hljs-title">async</span>` <span class="hljs-title">function</span> <span class="hljs-title">like</span> `<span class="hljs-title">ovenReady</span>` <span class="hljs-title">to</span> <span class="hljs-title">complete</span> <span class="hljs-title">and</span> <span class="hljs-title">return</span> <span class="hljs-title">data</span> <span class="hljs-title">before</span> <span class="hljs-title">moving</span> <span class="hljs-title">on</span> <span class="hljs-title">to</span> <span class="hljs-title">the</span> <span class="hljs-title">next</span> <span class="hljs-title">task</span> <span class="hljs-title">inside</span> <span class="hljs-title">a</span> <span class="hljs-title">parent</span> <span class="hljs-title">async</span> <span class="hljs-title">function</span>. <span class="hljs-title">We</span> <span class="hljs-title">see</span> <span class="hljs-title">this</span> <span class="hljs-title">when</span> <span class="hljs-title">the</span> `<span class="hljs-title">console</span>.<span class="hljs-title">log</span>(<span class="hljs-params">response</span>)` <span class="hljs-title">statement</span> <span class="hljs-title">does</span> <span class="hljs-title">not</span> <span class="hljs-title">execute</span> <span class="hljs-title">until</span> `<span class="hljs-title">ovenReady</span>` <span class="hljs-title">has</span> <span class="hljs-title">returned</span> <span class="hljs-title">a</span> <span class="hljs-title">response</span>. 

## <span class="hljs-title">If</span> <span class="hljs-title">the</span> <span class="hljs-title">pizza</span> <span class="hljs-title">example</span> <span class="hljs-title">doesn</span>'<span class="hljs-title">t</span> <span class="hljs-title">cut</span> <span class="hljs-title">it</span>...

<span class="hljs-title">I</span> <span class="hljs-title">know</span> <span class="hljs-title">everyday</span> <span class="hljs-title">examples</span> <span class="hljs-title">help</span> <span class="hljs-title">some</span> <span class="hljs-title">of</span> <span class="hljs-title">us</span>, <span class="hljs-title">but</span> <span class="hljs-title">others</span> <span class="hljs-title">may</span> <span class="hljs-title">just</span> <span class="hljs-title">prefer</span> <span class="hljs-title">real</span> <span class="hljs-title">code</span>. 

<span class="hljs-title">Therefore</span>, <span class="hljs-title">I</span>'<span class="hljs-title">m</span> <span class="hljs-title">going</span> <span class="hljs-title">to</span> <span class="hljs-title">provide</span> <span class="hljs-title">a</span> <span class="hljs-title">less</span> <span class="hljs-title">abstract</span> <span class="hljs-title">async</span> <span class="hljs-title">and</span> <span class="hljs-title">await</span> <span class="hljs-title">JavaScript</span> <span class="hljs-title">example</span> <span class="hljs-title">below</span> <span class="hljs-title">that</span> <span class="hljs-title">requests</span> <span class="hljs-title">data</span> <span class="hljs-title">with</span> <span class="hljs-title">the</span> <span class="hljs-title">Fetch</span> <span class="hljs-title">API</span>:

## <span class="hljs-title">Code</span> <span class="hljs-title">Example</span> <span class="hljs-title">of</span> <span class="hljs-title">Async</span>/<span class="hljs-title">Await</span> <span class="hljs-title">in</span> <span class="hljs-title">JavaScript</span>

```<span class="hljs-title">js</span>
<span class="hljs-title">const</span> <span class="hljs-title">getTheData</span> = <span class="hljs-title">async</span> (<span class="hljs-params"></span>) =&gt; </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://jsonplaceholder.typicode.com/users'</span>);
    <span class="hljs-keyword">if</span> (!response.ok) <span class="hljs-keyword">throw</span> <span class="hljs-built_in">Error</span>();
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-comment">// do something with this data... save to db, update the DOM, etc.</span>
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'You will see this last.'</span>)
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.error(err);
    }
} 

getTheData();
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'You will see this first.'</span>);
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>I hope I have helped you understand async and await in JavaScript. </p>
<p>I know it can take a while to fully grasp. </p>
<p>Start preheating your oven for the pizza you're craving and look at some more async and await examples while you wait for the beep!</p>
<p>I'll leave you with a tutorial from my Youtube channel. The video gives a deeper explanation and more code examples including a discussion of callbacks, promises, thenables and the Fetch API along with async &amp; await:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/VmQ6dHvnKIM" 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>
 ]]>
                </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[ Node.js Async Await Tutorial – With Asynchronous JavaScript Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Stanley Nguyen One of the hardest concepts to wrap your head around when you're first learning JavaScript is the asynchronous processing model of the language. For the majority of us, learning asynchronous programming looks pretty much like this ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/node-js-async-await-tutorial-with-asynchronous-javascript-examples/</link>
                <guid isPermaLink="false">66d4614b38f2dc3808b79107</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 04 May 2021 16:07:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/yoda.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Stanley Nguyen</p>
<p>One of the hardest concepts to wrap your head around when you're first learning JavaScript is the asynchronous processing model of the language. For the majority of us, learning asynchronous programming looks pretty much like this</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/async.png" alt="Image" width="600" height="400" loading="lazy">
<em>If your first time working with async wasn't like this, please consider yourself a genius</em></p>
<p>As hard as it is to pick up, async programming is critical to learn if you want to use JavaScript and Node.js to build web applications and servers – because JS code is <strong>asynchronous by default</strong>.</p>
<h2 id="heading-asynchronous-programming-fundamentals">Asynchronous Programming Fundamentals</h2>
<p>So what exactly is the asynchronous processing model, or the <code>non-blocking I/O</code> model (which you've likely heard of if you're a Node.js user)? </p>
<p>Here's a TL;DR description: in an async processing model, when your application engine interacts with external parties (like a file system or network), it doesn't wait until getting a result from those parties. Instead, it continues on to subsequent tasks and only comes back to those previous external parties once it's gotten a signal of a result.</p>
<p>To understand the default async processing model of Node.js, let's have a look at a hypothetical Santa's workshop. Before any work can begin, Santa will have to read each of the lovely letters from kids around the world.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/santa-01.png" alt="Santa reading letter for workshop" width="600" height="400" loading="lazy"></p>
<p>He will then figure out the requested gift, translate the item name into <a target="_blank" href="https://en.wikipedia.org/wiki/Elvish_languages">the Elvish language</a>, and then pass the instruction to each of our hard working elves who have different specialisations: wooden toys for Red, stuffed toys for Blue, and robotic toys for Green.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/santa-02.png" alt="Santa passing instruction to Red" width="600" height="400" loading="lazy"></p>
<p>This year, due to <a target="_blank" href="https://en.wikipedia.org/wiki/COVID-19_pandemic">the COVID-19 pandemic</a>, only half Santa's elves can come to his workshop to help. Still, because he's wise, Santa decides that instead of waiting for each elf to finish preparing a gift (that is, working synchronously), he will continue translating and passing out instructions from his pile of letters.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/santa-03.png" alt="Santa passing instruction to Blue" width="600" height="400" loading="lazy"></p>
<p>So on and so forth...</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/santa-04.png" alt="Santa continue passing out instructions" width="600" height="400" loading="lazy"></p>
<p>As he is just about to read another letter, Red informs Santa that he has completed<br>preparing the first gift. Santa then receives the present from Red, and puts it to one side.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/santa-05.png" alt="Santa receiving Red's present" width="600" height="400" loading="lazy"></p>
<p>And then he continues translating and passing instructions from the next letter.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/santa-06.png" alt="Santa passing instruction to Green" width="600" height="400" loading="lazy"></p>
<p>As he only needs to wrap a pre-made flying robot, Green can quickly finish preparation and pass the present to Santa.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/santa-07.png" alt="Santa receiving Green's present" width="600" height="400" loading="lazy"></p>
<p>After a whole day of hard and asynchronous work, Santa and the elves manage to complete all present preparation. With his improved asynchronous model of working, Santa's workshop is finished in record time despite being hard-hit by the pandemic.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/santa-08.png" alt="Santa's gotten all the presents" width="600" height="400" loading="lazy"></p>
<p>So that's the basic idea of an asynchronous or non-blocking I/O processing model. Now let's see how it's done in Node.js specifically.</p>
<h2 id="heading-the-nodejs-event-loop">The Node.js Event Loop</h2>
<p>You might have heard that Node.js is single-threaded. However, to be exact, only the event loop in Node.js, which interacts with a pool of background C++ worker threads, is single-threaded. There are four important components to the Node.js processing model:</p>
<ul>
<li>Event Queue: Tasks that are declared in a program, or returned from the processing thread pool via <a target="_blank" href="https://nodejs.org/en/knowledge/getting-started/control-flow/what-are-callbacks/">callbacks</a>. (The equivalent of this in our Santa's workshop is the pile of letters for Santa.)</li>
<li>Event Loop: The main Node.js thread that facilitates event queues and worker thread pools to carry out operations – both async and synchronous. (This is Santa. 🎅)</li>
<li>Background thread pool: These threads do the actual processing of tasks, which<br>might be I/O blocking (for example calling and waiting for a response from an external API). (These are the hardworking elves 🧝🧝‍♀️🧝‍♂️ from our workshop.)</li>
</ul>
<p>You can visualize this processing model as below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/processing-model.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram courtesy of c-sharpcorner.com</em></p>
<p>Let's look at an actual snippet of code to see these in action:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>);
https.get(<span class="hljs-string">"https://httpstat.us/200"</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`API returned status: <span class="hljs-subst">${res.statusCode}</span>`</span>);
});
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"from the other side"</span>);
</code></pre>
<p>If we execute the above piece of code, we would get this in our standard output:</p>
<pre><code class="lang-bash">Hello
from the other side
API returned status: 200
</code></pre>
<p>So how does the Node.js engine carry out the above snippet of code? It starts with three functions in the call stack:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/execution-01-1.png" alt="Processing starts with 3 functions in the call stack" width="600" height="400" loading="lazy"></p>
<p>"Hello" is then printed to the console with the corresponding function call removed from the stack.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/execution-02-1.png" alt="Hello console log removed from stack" width="600" height="400" loading="lazy"></p>
<p>The function call to <code>https.get</code> (that is, making a get request to the corresponding URL) is then executed and delegated to the worker thread pool with a callback attached.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/execution-03.png" alt="https.get delegated to worker pool" width="600" height="400" loading="lazy"></p>
<p>The next function call to <code>console.log</code> gets executed, and "from the other side" is printed to the console.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/execution-04.png" alt="Next console.log get executed" width="600" height="400" loading="lazy"></p>
<p>Now that the network call has returned a response, the callback function call will then get queued inside the callback queue. Note that this step could happen before the immediate previous step (that is, "from the other side" getting printed), though normally that's not the case.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/execution-05.png" alt="Network call completes and callback queued" width="600" height="400" loading="lazy"></p>
<p>The callback then gets put inside our call stack:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/execution-06.png" alt="Callback put inside call stack" width="600" height="400" loading="lazy"></p>
<p>and then we will see "API returned status: 200" in our console, like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/execution-07.png" alt="Status code printed out" width="600" height="400" loading="lazy"></p>
<p>By facilitating the callback queue and call stack, the event loop in Node.js efficiently executes our JavaScript code in an asynchronous way.</p>
<h2 id="heading-a-synchronous-history-of-javascript-amp-nodejs-asyncawait">A synchronous history of JavaScript &amp; Node.js async/await</h2>
<p>Now that you have good understanding of asynchronous execution and the inner-workings of the Node.js event loop, let's dive into async/await in JavaScript. We'll look at how it's worked through time, from the original callback-driven implementation to the latest shiny async/await keywords.</p>
<h3 id="heading-callbacks-in-javascript">Callbacks in JavaScript</h3>
<p>The OG way of handling the asynchronous nature of JavaScript engines was through callbacks. Callbacks are basically functions which will be executed, <strong>usually</strong>, at the end of synchronous or I/O blocking operations. </p>
<p>A straightforward example of this pattern is the built-in <code>setTimeout</code> function that will wait for a certain number of milliseconds before executing the callback.</p>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">2000</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>);
});
</code></pre>
<p>While it's convenient to just attach callbacks to blocking operations, this pattern also introduces a couple of problems:</p>
<ul>
<li>Callback hell</li>
<li>Inversion of control (not the good kind!)</li>
</ul>
<h4 id="heading-what-is-callback-hell">What is callback hell?</h4>
<p>Let's look at an example with Santa and his elves again. To prepare a present, Santa's workshop would have to carry out a few different steps (with each taking different amounts of time simulated using <code>setTimeout</code>):</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">translateLetter</span>(<span class="hljs-params">letter, callback</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">2000</span>, <span class="hljs-function">() =&gt;</span> {
    callback(letter.split(<span class="hljs-string">""</span>).reverse().join(<span class="hljs-string">""</span>));
  });
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">assembleToy</span>(<span class="hljs-params">instruction, callback</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> toy = instruction.split(<span class="hljs-string">""</span>).reverse().join(<span class="hljs-string">""</span>);
    <span class="hljs-keyword">if</span> (toy.includes(<span class="hljs-string">"wooden"</span>)) {
      <span class="hljs-keyword">return</span> callback(<span class="hljs-string">`polished <span class="hljs-subst">${toy}</span>`</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (toy.includes(<span class="hljs-string">"stuffed"</span>)) {
      <span class="hljs-keyword">return</span> callback(<span class="hljs-string">`colorful <span class="hljs-subst">${toy}</span>`</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (toy.includes(<span class="hljs-string">"robotic"</span>)) {
      <span class="hljs-keyword">return</span> callback(<span class="hljs-string">`flying <span class="hljs-subst">${toy}</span>`</span>);
    }
    callback(toy);
  });
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wrapPresent</span>(<span class="hljs-params">toy, callback</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">1000</span>, <span class="hljs-function">() =&gt;</span> {
    callback(<span class="hljs-string">`wrapped <span class="hljs-subst">${toy}</span>`</span>);
  });
}
</code></pre>
<p>These steps need to be carried out in a specific order:</p>
<pre><code class="lang-js">translateLetter(<span class="hljs-string">"wooden truck"</span>, <span class="hljs-function">(<span class="hljs-params">instruction</span>) =&gt;</span> {
  assembleToy(instruction, <span class="hljs-function">(<span class="hljs-params">toy</span>) =&gt;</span> {
    wrapPresent(toy, <span class="hljs-built_in">console</span>.log);
  });
});
<span class="hljs-comment">// This will produced a "wrapped polished wooden truck" as the final result</span>
</code></pre>
<p>As we do things this way, adding more steps to the process would mean pushing the inner callbacks to the right and ending up in callback hell like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/callback-hell.jpeg" alt="Callback Hell" width="600" height="400" loading="lazy"></p>
<p>Callbacks look sequential, but at times the execution order doesn't follow what is shown on your screen. With multiple layers of nested callbacks, you can easily lose track of the big picture of the whole program flow and produce more bugs or just become slower when writing your code.</p>
<p>So how do you solve this problem? Simply modularise the nested callbacks into named functions and you will have a nicely left-aligned program that's easy to read.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">assembleCb</span>(<span class="hljs-params">toy</span>) </span>{
  wrapPresent(toy, <span class="hljs-built_in">console</span>.log);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">translateCb</span>(<span class="hljs-params">instruction</span>) </span>{
  assembleToy(instruction, assembleCb);
}
translateLetter(<span class="hljs-string">"wooden truck"</span>, translateCb);
</code></pre>
<h4 id="heading-inversion-of-control">Inversion of Control</h4>
<p>Another problem with the callback pattern is that you don't decide how the higher-order functions will execute your callbacks. They might execute it at the end of the function, which is conventional, but they could also execute it at the start of the function or execute it multiple times. </p>
<p>Basically, you are at the mercy of your dependency owners, and you might never know when they will break your code.</p>
<p>To solve this problem, as a dependency user, there's not much you can do about it. However, if you're ever a dependency owner yourself, please always:</p>
<ul>
<li>Stick to the conventional callback signature with error as the first argument</li>
<li>Execute a callback only once at the end of your higher-order function</li>
<li>Document anything out-of-convention that is absolutely required and always aim for backward compatibility</li>
</ul>
<h3 id="heading-promises-in-javascript">Promises in JavaScript</h3>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a> were created to solve these above mentioned problems with callbacks. Promises make sure that JavaScript users:</p>
<ul>
<li>Stick to a specific convention with their signature <code>resolve</code> and <code>reject</code> functions.</li>
<li>Chain the callback functions to a well-aligned and top-down flow.</li>
</ul>
<p>Our previous example with Santa's workshop preparing presents can be rewritten with promises like so:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">translateLetter</span>(<span class="hljs-params">letter</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-number">2000</span>, <span class="hljs-function">() =&gt;</span> {
      resolve(letter.split(<span class="hljs-string">""</span>).reverse().join(<span class="hljs-string">""</span>));
    });
  });
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">assembleToy</span>(<span class="hljs-params">instruction</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-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">const</span> toy = instruction.split(<span class="hljs-string">""</span>).reverse().join(<span class="hljs-string">""</span>);
      <span class="hljs-keyword">if</span> (toy.includes(<span class="hljs-string">"wooden"</span>)) {
        <span class="hljs-keyword">return</span> resolve(<span class="hljs-string">`polished <span class="hljs-subst">${toy}</span>`</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (toy.includes(<span class="hljs-string">"stuffed"</span>)) {
        <span class="hljs-keyword">return</span> resolve(<span class="hljs-string">`colorful <span class="hljs-subst">${toy}</span>`</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (toy.includes(<span class="hljs-string">"robotic"</span>)) {
        <span class="hljs-keyword">return</span> resolve(<span class="hljs-string">`flying <span class="hljs-subst">${toy}</span>`</span>);
      }
      resolve(toy);
    });
  });
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wrapPresent</span>(<span class="hljs-params">toy</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-number">1000</span>, <span class="hljs-function">() =&gt;</span> {
      resolve(<span class="hljs-string">`wrapped <span class="hljs-subst">${toy}</span>`</span>);
    });
  });
}
</code></pre>
<p>with the steps being carried out nicely in a chain:</p>
<pre><code class="lang-js">translateLetter(<span class="hljs-string">"wooden truck"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">instruction</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> assembleToy(instruction);
  })
  .then(<span class="hljs-function">(<span class="hljs-params">toy</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> wrapPresent(toy);
  })
  .then(<span class="hljs-built_in">console</span>.log);
<span class="hljs-comment">// This would produce the exact same present: wrapped polished wooden truck</span>
</code></pre>
<p>However, promises are not without problems either. Data in each eye of our chain have a different scope and only have access data passed from the immediate previous step or parent scope. </p>
<p>For example, our gift-wrapping step might want to use data from the translation step:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wrapPresent</span>(<span class="hljs-params">toy, instruction</span>) </span>{
  <span class="hljs-keyword">return</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-number">1000</span>, <span class="hljs-function">() =&gt;</span> {
      resolve(<span class="hljs-string">`wrapped <span class="hljs-subst">${toy}</span> with instruction: "<span class="hljs-subst">${instruction}</span>`</span>);
    });
  });
}
</code></pre>
<p>This is rather <a target="_blank" href="https://livebook.manning.com/book/c-plus-plus-concurrency-in-action/chapter-3/1">a classic "memory sharing" problem with threading</a>. To solve this, instead of using variables in the parent's scope, we should use <code>Promise.all</code> and <a target="_blank" href="https://blog.golang.org/codelab-share">"share data by communicating, rather than communicate by sharing data"</a>.</p>
<pre><code class="lang-js">translateLetter(<span class="hljs-string">"wooden truck"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">instruction</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.all([assembleToy(instruction), instruction]);
  })
  .then(<span class="hljs-function">(<span class="hljs-params">toy, instruction</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> wrapPresent(toy, instruction);
  })
  .then(<span class="hljs-built_in">console</span>.log);
<span class="hljs-comment">// This would produce the present: wrapped polished wooden truck with instruction: "kcurt nedoow"</span>
</code></pre>
<h3 id="heading-asyncawait-in-javascript">Async/Await in JavaScript</h3>
<p>Last but definitely not least, the shiniest kid around the block is async/await. It is very easy to use but it also has some risks.</p>
<p>Async/await solves the memory sharing problems of promises by having everything under the same scope. Our previous example can be rewritten easily like so:</p>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> instruction = <span class="hljs-keyword">await</span> translateLetter(<span class="hljs-string">"wooden truck"</span>);
  <span class="hljs-keyword">const</span> toy = <span class="hljs-keyword">await</span> assembleToy(instruction);
  <span class="hljs-keyword">const</span> present = <span class="hljs-keyword">await</span> wrapPresent(toy, instruction);
  <span class="hljs-built_in">console</span>.log(present);
})();
<span class="hljs-comment">// This would produce the present: wrapped polished wooden truck with instruction: "kcurt nedoow"</span>
</code></pre>
<p>However, as much as it's easy to write asynchronous code with async/await, it's also easy to make mistakes that create performance loopholes. </p>
<p>Let's now localise our example Santa's workshop scenario to wrapping presents and loading them on the sleigh.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wrapPresent</span>(<span class="hljs-params">toy</span>) </span>{
  <span class="hljs-keyword">return</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-number">5000</span> * <span class="hljs-built_in">Math</span>.random(), <span class="hljs-function">() =&gt;</span> {
      resolve(<span class="hljs-string">`wrapped <span class="hljs-subst">${toy}</span>`</span>);
    });
  });
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadPresents</span>(<span class="hljs-params">presents</span>) </span>{
  <span class="hljs-keyword">return</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-number">5000</span>, <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">let</span> itemList = <span class="hljs-string">""</span>;
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; presents.length; i++) {
        itemList += <span class="hljs-string">`<span class="hljs-subst">${i}</span>. <span class="hljs-subst">${presents[i]}</span>\n`</span>;
      }
    });
  });
}
</code></pre>
<p>A common mistake you might make is carrying out the steps this way:</p>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> presents = [];
  presents.push(<span class="hljs-keyword">await</span> wrapPresent(<span class="hljs-string">"wooden truck"</span>));
  presents.push(<span class="hljs-keyword">await</span> wrapPresent(<span class="hljs-string">"flying robot"</span>));
  presents.push(<span class="hljs-keyword">await</span> wrapPresent(<span class="hljs-string">"stuffed elephant"</span>));
  <span class="hljs-keyword">const</span> itemList = <span class="hljs-keyword">await</span> loadPresents(presents);
  <span class="hljs-built_in">console</span>.log(itemList);
})();
</code></pre>
<p>But does Santa need to <code>await</code> for each of the presents to be wrapped one by one before loading? Definitely not! The presents should be wrapped concurrently. You might make this mistake often as it's so easy to write <code>await</code> without thinking about the blocking nature of the keyword.</p>
<p>To solve this problem, we should bundle the gift wrapping steps together and execute them all at once:</p>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> presents = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all([
    wrapPresent(<span class="hljs-string">"wooden truck"</span>),
    wrapPresent(<span class="hljs-string">"flying robot"</span>),
    wrapPresent(<span class="hljs-string">"stuffed elephant"</span>),
  ]);
  <span class="hljs-keyword">const</span> itemList = <span class="hljs-keyword">await</span> loadPresents(presents);
  <span class="hljs-built_in">console</span>.log(itemList);
})();
</code></pre>
<p>Here are some recommended steps to tackle concurrency performance issue in your Node.js code:</p>
<ul>
<li>Identify hotspots with multiple consecutive awaits in your code</li>
<li>Check if they are dependent on each other (that is one function uses data returned from another)</li>
<li>Make independent function calls concurrent with <code>Promise.all</code></li>
</ul>
<h2 id="heading-wrapping-up-the-article-not-christmas-presents">Wrapping up (the article, not Christmas presents 😂)</h2>
<p>Congratulations on reaching the end of this article, I tried my best to make<br>this post shorter, but the async topic in JavaScript is just so broad. </p>
<p>Here are some key takeaways:</p>
<ul>
<li>Modularise your JavaScript callbacks to avoid callback hell</li>
<li>Stick to <a target="_blank" href="https://gist.github.com/sunnycmf/b2ad4f80a3b627f04ff2">the convention for JS callbacks</a></li>
<li>Share data by communicating through <code>Promise.all</code> when using promises</li>
<li>Be careful about the performance implication of async/await code</li>
</ul>
<p>We ❤️ JavaScript :)</p>
<h2 id="heading-thank-you-for-reading">Thank you for reading!</h2>
<p>Last but not least, if you like my writings, please head over to <a target="_blank" href="https://blog.stanleynguyen.me/">my blog</a> for similar commentaries and follow <a target="_blank" href="https://twitter.com/stanley_ngn">me on Twitter</a>. 🎉</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Learn JavaScript Promises and Async/Await in 20 Minutes ]]>
                </title>
                <description>
                    <![CDATA[ By Thu Nghiem On the web, many things tend to be time-consuming – if you query an API, it can take a while to receive a response. Therefore, asynchronous programming is an essential skill for developers. When working with asynchronous operations in J... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-promise-async-await-in-20-minutes/</link>
                <guid isPermaLink="false">66d46156246e57ac83a2c7e3</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ projects ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 01 Dec 2020 01:38:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/maxresdefault.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Thu Nghiem</p>
<p>On the web, many things tend to be time-consuming – if you query an API, it can take a while to receive a response. Therefore, asynchronous programming is an essential skill for developers.</p>
<p>When working with asynchronous operations in JavaScript, we often hear the term <code>Promise</code>. But it can be tricky to understand how they work and how to use them.</p>
<p>Unlike many traditional coding tutorials, in this tutorial we'll learn by doing. We'll complete four tasks by the end of the article:</p>
<ul>
<li>Task 1: Promise basics explained using my birthday</li>
<li>Task 2: Build a guessing game</li>
<li>Task 3: Fetch country info from an API</li>
<li>Task 4: Fetch a country's neighboring countries</li>
</ul>
<p>If you want to follow along, be sure to download the resources here: <a target="_blank" href="https://bit.ly/3m4bjWI">https://bit.ly/3m4bjWI</a></p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/J29jeuyMJ38" 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>
<h2 id="heading-task-1-promise-basics-explained-using-my-birthday">Task 1: Promise basics explained using my birthday</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/z51d1v0jf07b43bfhfuu.gif" alt="Alt Text" width="1876" height="998" loading="lazy"></p>
<p>My friend Kayo promises to make a cake for my birthday in two weeks.</p>
<p>If everything goes well and Kayo doesn't get sick, we'll have a certain number of cakes. (Cakes are a countable in this tutorial 😆). Otherwise, if Kayo gets sick, we'll have no cakes.</p>
<p>Either way, we're still going to have a party.</p>
<p>For this first task, we'll translate this story into code. First, let's create a function that returns a <code>Promise</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> onMyBirthday = <span class="hljs-function">(<span class="hljs-params">isKayoSick</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-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">if</span> (!isKayoSick) {
        resolve(<span class="hljs-number">2</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">"I am sad"</span>));
      }
    }, <span class="hljs-number">2000</span>);
  });
};
</code></pre>
<p>In JavaScript, we can create a new <code>Promise</code> with <code>new Promise()</code>, which takes in a function as an argument: <code>(resolve, reject) =&gt; {}</code>. </p>
<p>In this function, <code>resolve</code> and <code>reject</code> are callback functions that are provided by default in JavaScript.</p>
<p>Let's take a closer look at the code above.</p>
<p>When we run the <code>onMyBirthday</code> function, after <code>2000ms</code>:</p>
<ul>
<li>If Kayo is not sick, then we run <code>resolve</code> with <code>2</code> as the argument</li>
<li>If Kayo is sick then we run <code>reject</code> with <code>new Error("I am sad")</code> as the argument. Even though you can pass anything to <code>reject</code> as an argument, it's recommended to pass it an <code>Error</code> object.</li>
</ul>
<p>Now, because <code>onMyBirthday()</code> returns a <code>Promise</code>, we have access to the <code>then</code>, <code>catch</code>, and <code>finally</code> methods. </p>
<p>And we also have access to the arguments that were passed into <code>resolve</code> and <code>reject</code> earlier within <code>then</code> and <code>catch</code>.</p>
<p>Let's take a closer look at the code.</p>
<p>If Kayo is not sick:</p>
<pre><code class="lang-js">onMyBirthday(<span class="hljs-literal">false</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I have <span class="hljs-subst">${result}</span> cakes`</span>); <span class="hljs-comment">// In the console: I have 2 cakes  </span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(error); <span class="hljs-comment">// Does not run</span>
  })
  .finally(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Party"</span>); <span class="hljs-comment">// Shows in the console no matter what: Party</span>
  });
</code></pre>
<p>If Kayo is sick:</p>
<pre><code class="lang-js">onMyBirthday(<span class="hljs-literal">true</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I have <span class="hljs-subst">${result}</span> cakes`</span>); <span class="hljs-comment">// does not run </span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(error); <span class="hljs-comment">// in console: Error: I am sad</span>
  })
  .finally(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Party"</span>); <span class="hljs-comment">// Shows in the console no matter what: Party</span>
  });
</code></pre>
<p>Alright, so by now, I hope you get the basic idea of <code>Promise</code>. Let's move onto task 2.</p>
<h2 id="heading-task-2-build-a-guessing-game">Task 2: Build a guessing game</h2>
<p>The requirements:</p>
<ul>
<li>User story: A user can enter a number</li>
<li>User story: The system picks a random number from 1 to 6</li>
<li>User story: If the user's number is equal to a random number, give the user 2 points</li>
<li>User story: If the user's number is different than the random number by 1,<br>give the user 1 point. Otherwise, give the user 0 points</li>
<li>User story: The user can play the game as long as they want to</li>
</ul>
<p>For the first 4 user stories, let's create an <code>enterNumber</code> function and return a <code>Promise</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> enterNumber = <span class="hljs-function">() =&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-comment">// Let's start from here</span>
  });
};
</code></pre>
<p>The first thing we need to do is to ask for a number from user and pick a random number between 1 and 6:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> enterNumber = <span class="hljs-function">() =&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">const</span> userNumber = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">window</span>.prompt(<span class="hljs-string">"Enter a number (1 - 6):"</span>)); <span class="hljs-comment">// Ask the user to enter a number</span>
    <span class="hljs-keyword">const</span> randomNumber = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">6</span> + <span class="hljs-number">1</span>); <span class="hljs-comment">// Pick a random number between 1 and 6</span>
  });
};
</code></pre>
<p>Now, <code>userNumber</code> can enter a value, that is not a number. If so, let's call the <code>reject</code> function with an error:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> enterNumber = <span class="hljs-function">() =&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">const</span> userNumber = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">window</span>.prompt(<span class="hljs-string">"Enter a number (1 - 6):"</span>)); <span class="hljs-comment">// Ask user to enter a number</span>
    <span class="hljs-keyword">const</span> randomNumber = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">6</span> + <span class="hljs-number">1</span>); <span class="hljs-comment">// Pick a random number between 1 and 6</span>

    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">isNaN</span>(userNumber)) {
      reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Wrong Input Type"</span>)); <span class="hljs-comment">// If the user enters a value that is not a number, run reject with an error</span>
    }
  });
};
</code></pre>
<p>The next thing we want to do is to check if the <code>userNumber</code> is equal to <code>randomNumber</code>, if so, we want give user 2 points and we can run the <code>resolve</code> function passing an object <code>{ points: 2, randomNumber }</code>. Notice here that we also want to know the <code>randomNumber</code> when the Promise is resolved</p>
<p>If the <code>userNumber</code> is different than <code>randomNumber</code> by one, then we give the user 1 point. Otherwise, we give the user 0 points:</p>
<pre><code class="lang-js"><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">const</span> userNumber = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">window</span>.prompt(<span class="hljs-string">"Enter a number (1 - 6):"</span>)); <span class="hljs-comment">// Ask the user to enter a number</span>
  <span class="hljs-keyword">const</span> randomNumber = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">6</span> + <span class="hljs-number">1</span>); <span class="hljs-comment">// Pick a random number between 1 and 6</span>

  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">isNaN</span>(userNumber)) {
    reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Wrong Input Type"</span>)); <span class="hljs-comment">// If the user enters a value that is not a number, run reject with an error</span>
  }

  <span class="hljs-keyword">if</span> (userNumber === randomNumber) {
    <span class="hljs-comment">// If the user's number matches the random number, return 2 points</span>
    resolve({
      <span class="hljs-attr">points</span>: <span class="hljs-number">2</span>,
      randomNumber,
    });
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (
    userNumber === randomNumber - <span class="hljs-number">1</span> ||
    userNumber === randomNumber + <span class="hljs-number">1</span>
  ) {
    <span class="hljs-comment">// If the user's number is different than the random number by 1, return 1 point</span>
    resolve({
      <span class="hljs-attr">points</span>: <span class="hljs-number">1</span>,
      randomNumber,
    });
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// Else return 0 points</span>
    resolve({
      <span class="hljs-attr">points</span>: <span class="hljs-number">0</span>,
      randomNumber,
    });
  }
});
</code></pre>
<p>Alright, let's also create another function to ask if the user wants to continue the game:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> continueGame = <span class="hljs-function">() =&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</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">window</span>.confirm(<span class="hljs-string">"Do you want to continue?"</span>)) { <span class="hljs-comment">// Ask if the user want to continue the game with a confirm modal</span>
      resolve(<span class="hljs-literal">true</span>);
    } <span class="hljs-keyword">else</span> {
      resolve(<span class="hljs-literal">false</span>);
    }
  });
};
</code></pre>
<p>Notice here that we create a <code>Promise</code>, but it does not use the <code>reject</code> callback. This is totally fine.</p>
<p>Now let's create a function to handle the guess:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> handleGuess = <span class="hljs-function">() =&gt;</span> {
  enterNumber() <span class="hljs-comment">// This returns a Promise</span>
    .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
      alert(<span class="hljs-string">`Dice: <span class="hljs-subst">${result.randomNumber}</span>: you got <span class="hljs-subst">${result.points}</span> points`</span>); <span class="hljs-comment">// When resolve is run, we get the points and the random number </span>

      <span class="hljs-comment">// Let's ask the user if they want to continue the game</span>
      continueGame().then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (result) {
          handleGuess(); <span class="hljs-comment">// If yes, we run handleGuess again</span>
        } <span class="hljs-keyword">else</span> {
          alert(<span class="hljs-string">"Game ends"</span>); <span class="hljs-comment">// If no, we show an alert</span>
        }
      });
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> alert(error));
};

handleGuess(); <span class="hljs-comment">// Run handleGuess function</span>
</code></pre>
<p>Here when we call <code>handleGuess</code>, <code>enterNumber()</code> now returns a <code>Promise</code>:</p>
<ul>
<li>If the <code>Promise</code> is resolved, we call the <code>then</code> method and show an alert message. We also ask if the user wants to continue.</li>
<li>If the <code>Promise</code> is rejected, we show an alert message with the error.</li>
</ul>
<p>As you can see, the code is quite difficult to read.</p>
<p>Let's refactor the <code>handleGuess</code> function a bit using the <code>async/await</code> syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> handleGuess = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> enterNumber(); <span class="hljs-comment">// Instead of the then method, we can get the result directly by just putting await before the promise</span>

    alert(<span class="hljs-string">`Dice: <span class="hljs-subst">${result.randomNumber}</span>: you got <span class="hljs-subst">${result.points}</span> points`</span>);

    <span class="hljs-keyword">const</span> isContinuing = <span class="hljs-keyword">await</span> continueGame();

    <span class="hljs-keyword">if</span> (isContinuing) {
      handleGuess();
    } <span class="hljs-keyword">else</span> {
      alert(<span class="hljs-string">"Game ends"</span>);
    }
  } <span class="hljs-keyword">catch</span> (error) { <span class="hljs-comment">// Instead of catch method, we can use the try, catch syntax</span>
    alert(error);
  }
};
</code></pre>
<p>You can see that we created an <code>async</code> function by putting <code>async</code> before the brackets. Then in the <code>async</code> function:</p>
<ul>
<li>Instead of the <code>then</code> method, we can get the results directly just by putting <code>await</code> before the promise</li>
<li>Instead of the <code>catch</code> method, we can use the <code>try, catch</code> syntax</li>
</ul>
<p>Here's all the code for this task again for your reference:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> enterNumber = <span class="hljs-function">() =&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">const</span> userNumber = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">window</span>.prompt(<span class="hljs-string">"Enter a number (1 - 6):"</span>)); <span class="hljs-comment">// Ask the user to enter a number</span>
    <span class="hljs-keyword">const</span> randomNumber = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">6</span> + <span class="hljs-number">1</span>); <span class="hljs-comment">// Pick a random number between 1 and 6</span>

    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">isNaN</span>(userNumber)) {
      reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Wrong Input Type"</span>)); <span class="hljs-comment">// If the user enters a value that is not a number, run reject with an error</span>
    }

    <span class="hljs-keyword">if</span> (userNumber === randomNumber) { <span class="hljs-comment">// If the user's number matches the random number, return 2 points</span>
      resolve({
        <span class="hljs-attr">points</span>: <span class="hljs-number">2</span>,
        randomNumber,
      });
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (
      userNumber === randomNumber - <span class="hljs-number">1</span> ||
      userNumber === randomNumber + <span class="hljs-number">1</span>
    ) { <span class="hljs-comment">// If the user's number is different than the random number by 1, return 1 point</span>
      resolve({
        <span class="hljs-attr">points</span>: <span class="hljs-number">1</span>,
        randomNumber,
      });
    } <span class="hljs-keyword">else</span> { <span class="hljs-comment">// Else return 0 points</span>
      resolve({
        <span class="hljs-attr">points</span>: <span class="hljs-number">0</span>,
        randomNumber,
      });
    }
  });
};

<span class="hljs-keyword">const</span> continueGame = <span class="hljs-function">() =&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</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">window</span>.confirm(<span class="hljs-string">"Do you want to continue?"</span>)) { <span class="hljs-comment">// Ask if the user want to continue the game with a confirm modal</span>
      resolve(<span class="hljs-literal">true</span>);
    } <span class="hljs-keyword">else</span> {
      resolve(<span class="hljs-literal">false</span>);
    }
  });
};

<span class="hljs-keyword">const</span> handleGuess = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> enterNumber(); <span class="hljs-comment">// Instead of the then method, we can get the result directly by just putting await before the promise</span>

    alert(<span class="hljs-string">`Dice: <span class="hljs-subst">${result.randomNumber}</span>: you got <span class="hljs-subst">${result.points}</span> points`</span>);

    <span class="hljs-keyword">const</span> isContinuing = <span class="hljs-keyword">await</span> continueGame();

    <span class="hljs-keyword">if</span> (isContinuing) {
      handleGuess();
    } <span class="hljs-keyword">else</span> {
      alert(<span class="hljs-string">"Game ends"</span>);
    }
  } <span class="hljs-keyword">catch</span> (error) { <span class="hljs-comment">// Instead of catch method, we can use the try, catch syntax</span>
    alert(error);
  }
};

handleGuess(); <span class="hljs-comment">// Run handleGuess function</span>
</code></pre>
<p>Alright, we are done with the second task. Let's move on to the third one.</p>
<h2 id="heading-task-3-fetch-country-info-from-an-apihttpsrestcountrieseu">Task 3: Fetch country info from <a target="_blank" href="https://restcountries.eu/">an API</a></h2>
<p>You'll see <code>Promises</code> used a lot when fetching data from an API.</p>
<p>If you open <a target="_blank" href="https://restcountries.eu/rest/v2/alpha/col">https://restcountries.eu/rest/v2/alpha/col</a> in a new browser, you will see the country data in JSON format.  </p>
<p>By using the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">Fetch API</a>, we can fetch the data by:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://restcountries.eu/rest/v2/alpha/col"</span>); <span class="hljs-comment">// fetch() returns a promise, so we need to wait for it</span>

  <span class="hljs-keyword">const</span> country = <span class="hljs-keyword">await</span> res.json(); <span class="hljs-comment">// res is now only an HTTP response, so we need to call res.json()</span>

  <span class="hljs-built_in">console</span>.log(country); <span class="hljs-comment">// Columbia's data will be logged to the dev console</span>
};

fetchData();
</code></pre>
<p>Now that we have the country data we want, let's move onto the last task.</p>
<h2 id="heading-task-4-fetch-a-countrys-neighboring-countries">Task 4: Fetch a country's neighboring countries</h2>
<p>If you open task 4, you will see that we have a <code>fetchCountry</code> function, that fetches the data from the endpoint: <code>https://restcountries.eu/rest/v2/alpha/${alpha3Code}</code> where <code>alpha3code</code> is the code of the country.  </p>
<p>You also see that it will catch any <code>error</code> that might happen when getting the data.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Task 4: get the neigher countries of Columbia</span>

<span class="hljs-keyword">const</span> fetchCountry = <span class="hljs-keyword">async</span> (alpha3Code) =&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://restcountries.eu/rest/v2/alpha/<span class="hljs-subst">${alpha3Code}</span>`</span>
    );

    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();

    <span class="hljs-keyword">return</span> data;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
};
</code></pre>
<p>Let's create a <code>fetchCountryAndNeighbors</code> function and fetch Columbia's information by passing <code>col</code> as the <code>alpha3code</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fetchCountryAndNeighbors = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> columbia = <span class="hljs-keyword">await</span> fetchCountry(<span class="hljs-string">"col"</span>);

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

fetchCountryAndNeighbors();
</code></pre>
<p>Now, if you look in your console, you can see an object look like this:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/35vkx7gewawg05wfcmni.png" alt="Alt Text" width="1048" height="369" loading="lazy"></p>
<p>In the object, there is a <code>border</code> property which is a list of <code>alpha3codes</code> for Columbia's neighboring countries.</p>
<p>Now if we try to get the neighboring countries by:</p>
<pre><code class="lang-js">  <span class="hljs-keyword">const</span> neighbors = 
    columbia.borders.map(<span class="hljs-function">(<span class="hljs-params">border</span>) =&gt;</span> fetchCountry(border));
</code></pre>
<p>Then, <code>neighbors</code> will be an array of <code>Promise</code> objects.</p>
<p>When working with an array of promises, we need to use <code>Promise.all</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fetchCountryAndNeigbors = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> columbia = <span class="hljs-keyword">await</span> fetchCountry(<span class="hljs-string">"col"</span>);

  <span class="hljs-keyword">const</span> neighbors = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all(
    columbia.borders.map(<span class="hljs-function">(<span class="hljs-params">border</span>) =&gt;</span> fetchCountry(border))
  );

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

fetchCountryAndNeigbors();
</code></pre>
<p>In the <code>console</code>, we should be able to see list of country objects.</p>
<p>Here's all the code for task 4 again for your reference:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fetchCountry = <span class="hljs-keyword">async</span> (alpha3Code) =&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://restcountries.eu/rest/v2/alpha/<span class="hljs-subst">${alpha3Code}</span>`</span>
    );

    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();

    <span class="hljs-keyword">return</span> data;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
};

<span class="hljs-keyword">const</span> fetchCountryAndNeigbors = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> columbia = <span class="hljs-keyword">await</span> fetchCountry(<span class="hljs-string">"col"</span>);

  <span class="hljs-keyword">const</span> neighbors = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all(
    columbia.borders.map(<span class="hljs-function">(<span class="hljs-params">border</span>) =&gt;</span> fetchCountry(border))
  );

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

fetchCountryAndNeigbors();
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/34m9mus03v2zo9agn2bq.png" alt="Alt Text" width="1872" height="1032" loading="lazy"></p>
<p>After completing these 4 tasks, you can see that <code>Promise</code> is useful when it comes to asynchronous actions or things that are not happening at the same time.</p>
<p>You can see this in practice in one of my tutorials, where we build an application from scratch with React and Next.js:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/v8o9iJU5hEA" 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>
<h2 id="heading-about-me"><strong><strong>__</strong></strong> 🐣 About me <strong><strong>__</strong></strong></h2>
<ul>
<li>I am the founder of <a target="_blank" href="https://devchallenges.io/">DevChallenges</a></li>
<li>Subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCmSmLukBF--YrKZ2g4akYAQ?sub_confirmation=1">YouTube Channel</a></li>
<li>Follow me on <a target="_blank" href="https://twitter.com/thunghiemdinh">Twitter</a></li>
<li>Join <a target="_blank" href="https://discord.com/invite/3R6vFeM">Discord</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Async Await JavaScript Tutorial – How to Wait for a Function to Finish in JS ]]>
                </title>
                <description>
                    <![CDATA[ By Fredrik Strand Oseberg When does an asynchronous function finish? And why is this such a hard question to answer?  Well it turns out that understanding asynchronous functions requires a great deal of knowledge about how JavaScript works fundamenta... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/async-await-javascript-tutorial/</link>
                <guid isPermaLink="false">66d45eddb6b7f664236cbdc0</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 28 Sep 2020 22:02:46 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c987e740569d1a4ca1a5b.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Fredrik Strand Oseberg</p>
<p>When does an asynchronous function finish? And why is this such a hard question to answer? </p>
<p>Well it turns out that understanding asynchronous functions requires a great deal of knowledge about how JavaScript works fundamentally.</p>
<p>Let's go explore this concept, and learn a lot about JavaScript in the process.</p>
<p>Are you ready? Let's go.</p>
<h2 id="heading-what-is-asynchronous-code">What is asynchronous code?</h2>
<p>By design, JavaScript is a synchronous programming language. This means that when code is executed, JavaScript starts at the top of the file and runs through code line by line, until it is done. </p>
<p>The result of this design decision is that only one thing can happen at any one time. </p>
<p>You can think of this as if you were juggling six small balls. While you are juggling, your hands are occupied and can't handle anything else. </p>
<p>It's the same with JavaScript: once the code is running, it has its hands full with that code. We call this this kind of synchronous code <em>blocking</em>. Because it's effectively blocking other code from running.</p>
<p>Let's circle back to the juggling example. What would happen if you wanted to add another ball? Instead of six balls, you wanted to juggle seven balls. That's might be a problem.</p>
<p>You don't want to stop juggling, because it's just so much fun. But you can't go and get another ball either, because that would mean you'd have to stop. </p>
<p>The solution? Delegate the work to a friend or family member. They aren't juggling, so they can go and get the ball for you, then toss it into your juggling at a time when your hand is free and you are ready to add another ball mid-juggle. </p>
<p>This is what asynchronous code is. JavaScript is delegating the work to something else, then going about it's own business. Then when it's ready, it will receive the results back from the work. </p>
<h2 id="heading-who-is-doing-the-other-work">Who is doing the other work?</h2>
<p>Alright, so we know that JavaScript is synchronous and lazy. It doesn't want to do all of the work itself, so it farms it out to something else. </p>
<p>But who is this mysterious entity that works for JavaScript? And how does it get hired to work for JavaScript?</p>
<p>Well, let's take a look at an example of asynchronous code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> logName = <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Han"</span>)
}

<span class="hljs-built_in">setTimeout</span>(logName, <span class="hljs-number">0</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi there"</span>)
</code></pre>
<p>Running this code results in the following output in the console:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// in console</span>
Hi there
Han
</code></pre>
<p>Alright. What is going on?</p>
<p>It turns out that the way we farm out work in JavaScript is to use environment-specific functions and APIs. And this is a source of great confusion in JavaScript. </p>
<p><strong>JavaScript always runs in an environment.</strong> </p>
<p>Often, that environment is the browser. But it can also be on the server with NodeJS. But what on earth is the difference?</p>
<p>The difference – and this is important – is that the browser and the server (NodeJS), functionality-wise, are not equivalent. They are often similar, but they are not the same. </p>
<p>Let's illustrate this with an example. Let's say JavaScript is the protagonist of an epic fantasy book. Just an ordinary farm kid.</p>
<p>Now let's say that this farm kid found two suits of special armor that gave them powers beyond their own. </p>
<p>When they used the browser suit of armor, they gained access to a certain set of capabilities. </p>
<p>When they used the server suit of armor they gained access to another set of capabilities. </p>
<p>These suits have some overlap, because the creators of these suits had the same needs in certain places, but not in others.</p>
<p>This is what an environment is. A place where code is run, where there exist tools that are built on top of the existing JavaScript language. They are not a part of the language, but the line is often blurred because we use these tools every day when we write code.</p>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope">setTimeout</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch</a>, and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model">DOM</a> are all examples of Web APIs. (You can <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API">see the full list of Web APIs here.</a>) They are tools that are built into the browser, and that are made available to us when our code is run. </p>
<p>And because we always run JavaScript in an environment, it seems like these are part of the language. But they are not.</p>
<p>So if you've ever wondered why you can use fetch in JavaScript when you run it in the browser (but need to install a package when you run it in NodeJS), this is why. Someone thought fetch was a good idea, and built it as a tool for the NodeJS environment. </p>
<p>Confusing? Yes!</p>
<p>But now we can finally understand what takes on the work from JavaScript, and how it gets hired.</p>
<p>It turns out that it is the environment that takes on the work, and the way to get the environment to do that work, is to use functionality that belongs to the environment. For example <em>fetch</em> or <em>setTimeout</em> in the browser environment.</p>
<h2 id="heading-what-happens-to-the-work">What happens to the work?</h2>
<p>Great. So the environment takes on the work. Then what?</p>
<p>At some point you need to get the results back. But let's think about how this would work. </p>
<p>Let's go back to the juggling example from the beginning. Imagine you asked for a new ball, and a friend just started throwing the ball at you when you weren't ready. </p>
<p>That would be a disaster. Maybe you could get lucky and catch it and get it into your routine effectively. But theres a large chance that it may cause you to drop all of your balls and crash your routine. Wouldn't it be better if you gave strict instructions on when to receive the ball?</p>
<p>As it turns out, there are strict rules surrounding when JavaScript can receive delegated work. </p>
<p>Those rules are governed by the event loop and involve the microtask and macrotask queue. Yes, I know. It's a lot. But bear with me.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/autodraw-31_08_2020.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Alright. So when we delegate asynchronous code to the browser, the browser takes and runs the code and takes on that workload. But there may be multiple tasks that are given to the browser, so we need to make sure that we can prioritise these tasks.</p>
<p>This is where the microtask queue and the macrotask queue come in play. The browser will take the work, do it, then place the result in one of the two queues based on the type of work it receives.</p>
<p>Promises, for example, are placed in the microtask queue and have a higher priority. </p>
<p>Events and setTimeout are examples of work that is put in the macrotask queue, and have a lower priority.</p>
<p>Now once the work is done, and is placed in one of the two queues, the event loop will run back and forth and check whether or not JavaScript is ready to receive the results. </p>
<p>Only when JavaScript is done running all its synchronous code, and is good and ready, will the event loop start picking from the queues and handing the functions back to JavaScript to run. </p>
<p>So let's take a look at an example:</p>
<pre><code><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">"hello"</span>), <span class="hljs-number">0</span>) 

fetch(<span class="hljs-string">"https://someapi/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))

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"What soup?"</span>)
</code></pre><p>What will the order be here?</p>
<ol>
<li>Firstly, setTimeout is delegated to the browser, which does the work and puts the resulting function in the macrotask queue.</li>
<li>Secondly fetch is delegated to the browser, which takes the work. It retrieves the data from the endpoint and puts the resulting functions in the microtask queue.</li>
<li>Javascript logs out "What soup"?</li>
<li>The event loop checks whether or not JavaScript is ready to receive the results from the queued work.</li>
<li>When the console.log is done, JavaScript is ready. The event loop picks queued functions from the microtask queue, which has a higher priority, and gives them back to JavaScript to execute.</li>
<li>After the microtask queue is empty, the setTimeout callback is taken out of the macrotask queue and given back to JavaScript to execute.</li>
</ol>
<pre><code>In <span class="hljs-built_in">console</span>:
<span class="hljs-comment">// What soup?</span>
<span class="hljs-comment">// the data from the api</span>
<span class="hljs-comment">// hello</span>
</code></pre><h2 id="heading-promises">Promises</h2>
<p>Now you should have a good deal of knowledge about how asynchronous code is handled by JavaScript and the browser environment. So let's talk about promises.</p>
<p>A promise is a JavaScript construct that represents a future unknown value. Conceptually, a promise is just JavaScript promising to return <em>a value</em>. It could be the result from an API call, or it could be an error object from a failed network request. You're guaranteed to get something. </p>
<pre><code><span class="hljs-keyword">const</span> promise = <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">// Make a network request</span>
   <span class="hljs-keyword">if</span> (response.status === <span class="hljs-number">200</span>) {
      resolve(response.body)
   } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">const</span> error = { ... }
      reject(error)
   }
})

promise.then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(res)
}).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>A promise can have the following states: </p>
<ul>
<li>fulfilled - action successfully completed</li>
<li>rejected - action failed</li>
<li>pending - neither action has been completed </li>
<li>settled - has been fulfilled or rejected</li>
</ul>
<p>A promise receives a resolve and a reject function that can be called to trigger one of these states.</p>
<p>One of the big selling points of promises is that we can chain functions that we want to happen on success (resolve) or failure (reject): </p>
<ul>
<li>To register a function to run on success we use .then</li>
<li>To register a function to run on failure we use .catch</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Fetch returns a promise</span>
fetch(<span class="hljs-string">"https://swapi.dev/api/people/1"</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">"This function is run when the request succeeds"</span>, res)
    .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This function is run when the request fails"</span>, err)

<span class="hljs-comment">// Chaining multiple functions</span>
 fetch(<span class="hljs-string">"https://swapi.dev/api/people/1"</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> doSomethingWithResult(res))
    .then(<span class="hljs-function">(<span class="hljs-params">finalResult</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(finalResult))
    .catch((<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> doSomethingWithErr(err))
</code></pre>
<p>Perfect. Now let's take a closer look at what this looks like under the hood, using fetch as an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetch = <span class="hljs-function">(<span class="hljs-params">url, options</span>) =&gt;</span> {
  <span class="hljs-comment">// simplified</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">const</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest()
  <span class="hljs-comment">// ... make request</span>
  xhr.onload = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> options = {
        <span class="hljs-attr">status</span>: xhr.status,
        <span class="hljs-attr">statusText</span>: xhr.statusText
        ...
    }

    resolve(<span class="hljs-keyword">new</span> Response(xhr.response, options))
  }

  xhr.onerror = <span class="hljs-function">() =&gt;</span> {
    reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">"Request failed"</span>))
  }
}

 fetch(<span class="hljs-string">"https://swapi.dev/api/people/1"</span>)
   <span class="hljs-comment">// Register handleResponse to run when promise resolves</span>
    .then(handleResponse)
  .catch(handleError)

 <span class="hljs-comment">// conceptually, the promise looks like this now:</span>
 <span class="hljs-comment">// { status: "pending", onsuccess: [handleResponse], onfailure: [handleError] }</span>

 <span class="hljs-keyword">const</span> handleResponse = <span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
  <span class="hljs-comment">// handleResponse will automatically receive the response, ¨</span>
  <span class="hljs-comment">// because the promise resolves with a value and automatically injects into the function</span>
   <span class="hljs-built_in">console</span>.log(response)
 }

  <span class="hljs-keyword">const</span> handleError = <span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
  <span class="hljs-comment">// handleError will automatically receive the error, ¨</span>
  <span class="hljs-comment">// because the promise resolves with a value and automatically injects into the function</span>
   <span class="hljs-built_in">console</span>.log(response)
 }

<span class="hljs-comment">// the promise will either resolve or reject causing it to run all of the registered functions in the respective arrays</span>
<span class="hljs-comment">// injecting the value. Let's inspect the happy path:</span>

<span class="hljs-comment">// 1. XHR event listener fires</span>
<span class="hljs-comment">// 2. If the request was successfull, the onload event listener triggers</span>
<span class="hljs-comment">// 3. The onload fires the resolve(VALUE) function with given value</span>
<span class="hljs-comment">// 4. Resolve triggers and schedules the functions registered with .then</span>
</code></pre>
<p>So we can use promises to do asynchronous work, and to be sure that we can handle any result from those promises. That is the value proposition. If you want to know more about promises you can read more about them <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">here</a> and <a target="_blank" href="https://web.dev/promises/">here</a>.</p>
<p>When we use promises, we chain our functions onto the promise to handle the different scenarios.</p>
<p>This works, but we still need to handle our logic inside callbacks (nested functions) once we get our results back. What if we could use promises but write synchronous looking code? It turns out we can.</p>
<h2 id="heading-asyncawait">Async/Await</h2>
<p>Async/Await is a way of writing promises that allows us to write <em>asynchronous code in a synchronous way.</em> Let's have a look.</p>
<pre><code><span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos/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>Nothing has changed under the hood here. We are still using promises to fetch data, but now it looks synchronous, and we no longer have .then and .catch blocks. </p>
<p>Async / Await is actually just syntactic sugar providing a way to create code that is easier to reason about, without changing the underlying dynamic. </p>
<p>Let's take a look at how it works.</p>
<p>Async/Await lets us use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">generators</a> to <em>pause</em> the execution of a function. When we are using async / await we are not blocking because the function is yielding the control back over to the main program. </p>
<p>Then when the promise resolves we are using the generator to yield control back to the asynchronous function with the value from the resolved promise. </p>
<p><a target="_blank" href="https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch4.md">You can read more here for a great overview</a> of generators and asynchronous code.</p>
<p>In effect, we can now write asynchronous code that looks like synchronous code. Which means that it is easier to reason about, and we can use synchronous tools for error handling such as try / catch:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">async</span> () =&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://jsonplaceholder.typicode.com/todos/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)
    } <span class="hljs-keyword">catch</span> (err) {
       <span class="hljs-built_in">console</span>.log(err)
    }

}

getData()
</code></pre>
<p>Alright. So how do we use it? In order to use async / await we need to prepend the function with async. This does not make it an asynchronous function, it merely allows us to use await inside of it. </p>
<p>Failing to provide the async keyword will result in a syntax error when trying to use await inside a regular function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"We can use await in this function"</span>)
}
</code></pre>
<p>Because of this, we can not use async / await on top level code. But async and await are still just syntactic sugar over promises. So we can handle top level cases with promise chaining: </p>
<pre><code><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">let</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'http://apiurl.com'</span>);
}

<span class="hljs-comment">// getData is a promise</span>
getData().then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(res)).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>This exposes another interesting fact about async / await. When defining a function as async, <em>it will always return a promise.</em></p>
<p>Using async / await can seem like magic at first. But like any magic, it's just sufficiently advanced technology that has evolved over the years. Hopefully now you have a solid grasp of the fundamentals, and can use async / await with confidence.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>If you made it here, congrats. You just added a key piece of knowledge about JavaScript and how it works with its environments to your toolbox. </p>
<p>This is definitely a confusing subject, and the lines are not always clear. But now you hopefully have a grasp on how JavaScript works with asynchronous code in the browser, and a stronger grasp over both promises and async / await. </p>
<p>If you enjoyed this article, you might also enjoy my <a target="_blank" href="https://www.youtube.com/channel/UCZTeUahnA2GMoo_YpTBFo9A?view_as=subscriber">youtube channel</a>. I currently have a <a target="_blank" href="https://www.youtube.com/watch?v=kmvg9C8hVa0&amp;list=PL_kr51suci7XVVw4SJLZ0QQBAsL2K8Opy">web fundamentals series</a> going where I go through <a target="_blank" href="https://www.youtube.com/watch?v=0ykAOzJb-U8&amp;t=19s">HTTP</a>, <a target="_blank" href="https://www.youtube.com/watch?v=R5uwuG1wPR8">building web servers from scratch</a> and more. </p>
<p>There's also a series going on <a target="_blank" href="https://www.youtube.com/playlist?list=PL_kr51suci7WkVde-b09G4XHEWQrmzcpJ">building an entire app with React</a>, if that is your jam. And I plan to add much more content here in the future going in depth on JavaScript topics.</p>
<p>And if you want to say hi or chat about web development, you could always reach out to me on twitter at @foseberg. Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
