<?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[ promises - 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[ promises - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 29 May 2026 16:31:27 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/promises/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 JavaScript Promises Work – Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Many operations, such as network requests, are asynchronous in nature. One of the most useful and powerful tools for working with asynchronous code is the Promise. In this handbook, you'll learn all about JavaScript Promises and how to use them. Tabl... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-javascript-promises-handbook/</link>
                <guid isPermaLink="false">66ba565c194f72bcfe482c32</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joe Attardi ]]>
                </dc:creator>
                <pubDate>Tue, 13 Feb 2024 23:37:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/How-JavaScript-Promises-Work-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Many operations, such as network requests, are asynchronous in nature. One of the most useful and powerful tools for working with asynchronous code is the Promise. In this handbook, you'll learn all about JavaScript Promises and how to use them.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-a-promise">What is a Promise?</a></li>
<li><a class="post-section-overview" href="#heading-comparing-promises-to-other-async-patterns">Comparing Promises to Other Async Patterns</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-promise">How to Create a Promise</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-the-result-of-a-promise">How to Get the Result of a Promise</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-errors-with-then">How to Handle Errors with <code>then</code></a></li>
<li><a class="post-section-overview" href="#heading-promise-chaining">Promise Chaining</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-immediately-fulfilled-or-rejected-promises">How to Create Immediately Fulfilled or Rejected Promises</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-async-and-await">How to Use <code>async</code> and <code>await</code></a></li>
<li><a class="post-section-overview" href="#heading-promise-anti-patterns">Promise Anti-Patterns</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ol>
<h2 id="heading-what-is-a-promise">What is a Promise?</h2>
<p>Let's begin by looking at what a Promise is.</p>
<p>In simple terms, a Promise is an object representing an asynchronous operation. This object can tell you when the operation succeeds, or when it fails. </p>
<p>When you call a Promise-based API, the function returns a Promise object that will eventually provide the result of the operation.</p>
<h3 id="heading-promise-states">Promise states</h3>
<p>During its lifetime, a Promise can be in one of three states:</p>
<ul>
<li><strong>Pending</strong>: A Promise is pending while the operation is still in progress. It's in an idle state, waiting for the eventual result (or error).</li>
<li><strong>Fulfilled</strong>: The asynchronous task that returned the Promise completed successfully. A Promise is fulfilled with a value, which is the result of the operation.</li>
<li><strong>Rejected</strong>: If the asynchronous operation failed, the Promise is said to be rejected. A Promise is rejected with a <em>reason</em>. This typically is an <code>Error</code> object, but a Promise can be rejected with any value – even a simple number or string!</li>
</ul>
<p>A Promise starts out in the pending state, then depending on the result, will transition to either the fulfilled or rejected state. A Promise is said to be <em>settled</em> once it reaches either the fulfilled or rejected state.</p>
<p>Of course, there is no guarantee that the asynchronous task will ever complete. It's completely possible for a <code>Promise</code> to remain in the pending state forever, though this would be because of a bug in the asynchronous task's code.</p>
<h2 id="heading-comparing-promises-to-other-async-patterns">Comparing Promises to Other Async Patterns</h2>
<p>Promises behave a little differently from other asynchronous patterns in JavaScript. Before diving deeper into Promises, let's briefly compare Promises to these other techniques.</p>
<h3 id="heading-callback-functions">Callback functions</h3>
<p>A callback function is a function that you pass to another function. When the function you call has finished its work, it will execute your callback function with the result.</p>
<p>Imagine a function called <code>getUsers</code> which will make a network request to get an array of users. You can pass a callback function to <code>getUsers</code>, which will be called with the array of users once the network request is complete:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Preparing to get users'</span>);
getUsers(<span class="hljs-function"><span class="hljs-params">users</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Got users:'</span>, users);
});
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Users request sent'</span>);
</code></pre>
<p>First, the above code will print "Preparing to get users". Then it calls <code>getUsers</code> which will initiate the network request. But JavaScript doesn't wait for the request to complete. Instead, it immediately executes the next <code>console.log</code> statement.</p>
<p>Later, once the users have been loaded, your callback will be executed and "Got users" will be printed.</p>
<p>Some callback-based APIs, such as many Node.js APIs, use <em>error-first callbacks</em>. These callback functions take two arguments. The first argument is an error, and the second is the result. </p>
<p>Typically, only one of these will have a value, depending on the outcome of the operation. This is similar to the fulfilled and rejected Promise states.</p>
<p>The trouble with callback APIs is that of nesting. If you need to make multiple asynchronous calls in sequence, you’ll end up with nested function calls and callbacks.</p>
<p>Imagine you want to read a file, process some data from that file, then write a new file. All three of these tasks are asynchronous and use an imaginary callback based API.</p>
<pre><code class="lang-javascript">readFile(<span class="hljs-string">'sourceData.json'</span>, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    processData(data, <span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
        writeFile(result, <span class="hljs-string">'processedData.json'</span>, <span class="hljs-function">() =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Done processing'</span>);
        });
    });
});
</code></pre>
<p>It gets even more unwieldy with error handling. Imagine these functions used error-first callbacks:</p>
<pre><code class="lang-javascript">readFile(<span class="hljs-string">'sourceData.json'</span>, <span class="hljs-function">(<span class="hljs-params">error, data</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error reading file:'</span>, error);
        <span class="hljs-keyword">return</span>;
    }

    processData(data, <span class="hljs-function">(<span class="hljs-params">error, result</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (error) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error processing data:'</span>, error);
            <span class="hljs-keyword">return</span>;
        }

        writeFile(result, <span class="hljs-string">'processedData.json'</span>, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
            <span class="hljs-keyword">if</span> (error) {
                <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error writing file:'</span>, error);
                <span class="hljs-keyword">return</span>;
            }

            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Done processing'</span>);
        });
    });
});
</code></pre>
<p>Callback functions aren't typically used directly as an asynchronous mechanism in modern APIs, but as you'll soon see, they are the foundation for other types of asynchronous tools such as Promises.</p>
<h3 id="heading-events">Events</h3>
<p>An event is something that you can listen for and respond to. Some objects in JavaScript are event <em>emitters</em>, which means you can register event listeners on them. </p>
<p>In the DOM, many elements implement the <code>EventTarget</code> interface which provides <code>addEventListener</code> and <code>removeEventListener</code> methods.</p>
<p>A given type of event can occur more than once. For example, you can listen for the click event on a button:</p>
<pre><code class="lang-javascript">myButton.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'button was clicked!'</span>); 
});
</code></pre>
<p>Every time the button is clicked, the text "button was clicked!" will be printed to the console. </p>
<p><code>addEventListener</code> itself accepts a callback function. Whenever the event occurs, the callback is executed.</p>
<p>An object can emit multiple types of events. Consider an image object. If the image at the specified URL is loaded successfully, the <code>load</code> event is triggered. If there was an error, this event is not triggered and instead the <code>error</code> event is triggered.</p>
<pre><code class="lang-javascript">myImage.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Image was loaded'</span>);
});

myImage.addEventListener(<span class="hljs-string">'error'</span>, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
   <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Image failed to load:'</span>, error); 
});
</code></pre>
<p>Suppose the image already completed loading before you added the event listener. What do you think would happen? Nothing! One drawback of event-based APIs is that if you add an event listener after an event, your callback won't be executed. This makes sense, after all – you wouldn't want to receive all past click events when you add a click listener to a button.</p>
<p>Now that we've explored callbacks and events, let's take a closer look at Promises.</p>
<h2 id="heading-how-to-create-a-promise">How to Create a Promise</h2>
<p>You can create a Promise using the <code>new</code> keyword with the <code>Promise</code> constructor. The <code>Promise</code> constructor takes a callback function that takes two arguments, called <code>resolve</code> and <code>reject</code>. Each of these arguments is a function provided by the Promise, which are used to transition the Promise to either the fulfilled or rejected state.</p>
<p>Inside your callback, you perform your asynchronous work. If the task is successful, you call the <code>resolve</code> function with the final result. If there was an error, you call the <code>reject</code> function with the error.</p>
<p>Here's an example of creating a Promise that wraps the browser's <code>setTimeout</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wait</span>(<span class="hljs-params">duration</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, duration);
    });
}
</code></pre>
<p>The <code>resolve</code> function is passed as the first argument to <code>setTimeout</code>. After the time specified by <code>duration</code> has passed, the browser calls the <code>resolve</code> function which fulfills the Promise.</p>
<p>Note: In this example, the delay before the <code>resolve</code> function is called may be longer than the duration passed to the function. This is because <code>setTimeout</code> does not guarantee execution at the specified time.</p>
<p>It's important to note that often times, you won't actually need to construct your own Promise by hand. You will typically be working with Promises returned by other APIs.</p>
<h2 id="heading-how-to-get-the-result-of-a-promise">How to Get the Result of a Promise</h2>
<p>We've seen how to create a Promise, but how do you actually get the result of the asynchronous operation? To do this, you call <code>then</code> on the Promise object itself. <code>then</code> takes a callback function as its argument. When the Promise is fulfilled, the callback is executed with the result.</p>
<p>Let's see an example of this in action. Imagine a function called <code>getUsers</code> that asynchronously loads a list of user objects and returns a Promise. You can get the list of users by calling <code>then</code> on the Promise returned by <code>getUsers</code>.</p>
<pre><code class="lang-javascript">getUsers()
  .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">'Got users:'</span>, users);
  });
</code></pre>
<p>Just like with events or callback based APIs, your code will continue executing without waiting for the result. Some time later, when the users have been loaded, your callback is scheduled for execution.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Loading users'</span>);
getUsers()
  .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">'Got users:'</span>, users);
  });
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Continuing on'</span>);
</code></pre>
<p>In the above example, "Loading users" will be printed first. The next thing that is printed will be "Continuing on", because the <code>getUsers</code> call is still loading the users. Later, you'll see "Got users" printed.</p>
<h2 id="heading-how-to-handle-errors-with-then">How to Handle Errors with <code>then</code></h2>
<p>We've seen how to use <code>then</code> to get the result provided to the Promise, but what about errors? What happens if we fail to load the user list? </p>
<p>The <code>then</code> function actually takes a second argument, another callback. This is the error handler. If the Promise is rejected, this callback is executed with the rejection value.</p>
<pre><code class="lang-javascript">getUsers()
  .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">'Got users:'</span>, users);
  }, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Failed to load users:'</span>, error);  
  });
</code></pre>
<p>Since a Promise can only ever be either fulfilled or rejected, but not both, only one of these callback functions will be executed.</p>
<p>It's important to always handle errors when working with Promises. If you have a Promise rejection that isn't handled by an error callback, you'll get an exception in your console about an unhandled rejection, which can cause issues for your users at runtime.</p>
<h2 id="heading-promise-chaining">Promise Chaining</h2>
<p>What if you need to work with multiple Promises in series? Consider the earlier example where we loaded some data from a file, did some processing, and wrote the result to a new file. Suppose the <code>readFile</code>, <code>processData</code>, and <code>writeFile</code> functions used Promises instead of callbacks. </p>
<p>You might try something like this:</p>
<pre><code class="lang-javascript">readFile(<span class="hljs-string">'sourceData.json'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    processData(data)
      .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
        writeFile(result, <span class="hljs-string">'processedData.json'</span>)
          .then(<span class="hljs-function">() =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Done processing'</span>);
          });
      });
  });
</code></pre>
<p>This doesn't look great, and we still have the nesting issue that we had with the callback approach. Thankfully, there is a better way. You can chain Promises together in a flat sequence.</p>
<p>To see how this works, let's look deeper at how <code>then</code> works. The key idea is this: the <code>then</code> method returns <em>another Promise</em>. Whatever value you return from your <code>then</code> callback becomes the fulfilled value of this new Promise.</p>
<p>Consider a <code>getUsers</code> function that returns a Promise that gets fulfilled with an array of user objects. Suppose we call <code>then</code> on this Promise, and in the callback, return the first user in the array (<code>users[0]</code>):</p>
<pre><code class="lang-javascript">getUsers().then(<span class="hljs-function"><span class="hljs-params">users</span> =&gt;</span> users[<span class="hljs-number">0</span>]);
</code></pre>
<p>This whole expression, then, results in a new Promise that will be fulfilled with the first user object!</p>
<pre><code class="lang-javascript">getUsers()
  .then(<span class="hljs-function"><span class="hljs-params">users</span> =&gt;</span> users[<span class="hljs-number">0</span>])
  .then(<span class="hljs-function"><span class="hljs-params">firstUser</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'First user:'</span>, firstUser.username);
  });
</code></pre>
<p>This process of returning a Promise, calling <code>then</code>, and returning another value, resulting in another Promise, is called chaining.</p>
<p>Let's extend this idea. What if, instead of returning a value from the <code>then</code> handler, we returned another Promise? Consider again the file-processing example, where <code>readFile</code> and <code>processData</code> are both asynchronous functions that return Promises:</p>
<pre><code class="lang-javascript">readFile(<span class="hljs-string">'sourceData.json'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> processData(data));
</code></pre>
<p>The <code>then</code> handler calls <code>processData</code>, returning the resulting Promise. As before, this returns a new Promise. In this case, the new Promise will become fulfilled when the Promise returned by <code>processData</code> is fulfilled, giving you the same value. So the code in the above example would return a Promise that will be fulfilled with the processed data.</p>
<p>You can chain multiple Promises, one after the other, until you get to the final value you need:</p>
<pre><code class="lang-javascript">readFile(<span class="hljs-string">'sourceData.json'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> processData(data))
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> writeFile(result, <span class="hljs-string">'processedData.json'</span>))
  .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Done processing'</span>));
</code></pre>
<p>In the above example, the whole expression will result in a Promise that won't be fulfilled until after the processed data is written to a file. "Done processing!" will be printed to the console, and then the final Promise will become fulfilled.</p>
<h3 id="heading-error-handling-in-promise-chains">Error handling in Promise chains</h3>
<p>In our file-processing example, an error can occur at any stage in the process. You can handle an error from any step in the Promise chain by using the Promise's <code>catch</code> method. </p>
<pre><code class="lang-javascript">readFile(<span class="hljs-string">'sourceData.json'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> processData(data))
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> writeFile(result, <span class="hljs-string">'processedData.json'</span>))
  .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Done processing'</span>))
  .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 while processing:'</span>, error));
</code></pre>
<p>If one of the Promises in the chain is rejected, the callback function passed to <code>catch</code> will execute and the rest of the chain is skipped.</p>
<h3 id="heading-how-to-use-finally">How to use <code>finally</code></h3>
<p>You might have some code you want to execute regardless of the Promise result. For example, maybe you want to close a database or a file.</p>
<pre><code class="lang-javascript">openDatabase()
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> processData(data))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error'</span>))
  .finally(<span class="hljs-function">() =&gt;</span> closeDatabase());
</code></pre>
<h3 id="heading-how-to-use-promiseall">How to use <code>Promise.all</code></h3>
<p>Promise chains let you run multiple tasks in sequence, but what if you want to run multiple tasks at the same time, and wait until they all complete? The <code>Promise.all</code> method lets you do just that.</p>
<p><code>Promise.all</code> takes an array of Promises, and returns a new Promise. This Promise will be fulfilled once all of the other Promises are fulfilled. The fulfillment value is an array containing the fulfillment values of each Promise in the input array.</p>
<p>Suppose you have a function <code>loadUserProfile</code> that loads a user's profile data, and  another function <code>loadUserPosts</code> that loads a user's posts. They both take a user ID as the argument. There's a third function, <code>renderUserPage</code>, that needs both the profile and list of posts.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userId = <span class="hljs-number">100</span>;

<span class="hljs-keyword">const</span> profilePromise = loadUserProfile(userId);
<span class="hljs-keyword">const</span> postsPromise = loadUserPosts(userId);

<span class="hljs-built_in">Promise</span>.all([profilePromise, postsPromise])
  .then(<span class="hljs-function"><span class="hljs-params">results</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> [profile, posts] = results;
    renderUserPage(profile, posts);
  });
</code></pre>
<p>What about errors? If any of the Promises passed to <code>Promise.all</code> is rejected with an error, the resulting Promise is also rejected with that error. If any of the other Promises are fulfilled, those values are lost.</p>
<h3 id="heading-how-to-use-promiseallsettled">How to use <code>Promise.allSettled</code></h3>
<p>The <code>Promise.allSettled</code> method works similarly to <code>Promise.all</code>. The main difference is that the Promise returned by <code>Promise.allSettled</code> will never be rejected. </p>
<p>Instead, it is fulfilled with an array of objects, whose order corresponds to the order of the Promises in the input array. Each object has a <code>status</code> property which is either "fulfilled" or "rejected", depending on the result. </p>
<p>If <code>status</code> is "fulfilled", the object will also have a <code>value</code> property indicating the Promise's fulfillment value. If <code>status</code> is "rejected", the object will instead have a <code>reason</code> property which is the error or other object the Promise was rejected with.</p>
<p>Consider again a <code>getUser</code> function that takes a user ID and returns a Promise that is fulfilled with the user having that ID. You can use <code>Promise.allSettled</code> to load these in parallel, making sure to get all users that were loaded successfully.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.allSettled([
  getUser(<span class="hljs-number">1</span>),
  getUser(<span class="hljs-number">2</span>),
  getUser(<span class="hljs-number">3</span>)
]).then(<span class="hljs-function"><span class="hljs-params">results</span> =&gt;</span> {
   <span class="hljs-keyword">const</span> users = results
     .filter(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.status === <span class="hljs-string">'fulfilled'</span>)
     .map(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.value);
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Got users:'</span>, users);
});
</code></pre>
<p>You can make a general purpose <code>loadUsers</code> function that loads users, in parallel, given an array of user IDs. The function returns a Promise that is fulfilled with an array of all users that were successfully loaded.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params">userIds</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.allSettled(userIds.map(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> getUser(id)))
    .then(<span class="hljs-function"><span class="hljs-params">results</span> =&gt;</span> {
      <span class="hljs-keyword">return</span> results
        .filter(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.status === <span class="hljs-string">'fulfilled'</span>)
        .map(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.value);
    });
}
</code></pre>
<p>Then, you can just call <code>getUsers</code> with an array of user IDs:</p>
<pre><code class="lang-javascript">getUsers([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
    .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">'Got users:'</span>, users));
</code></pre>
<h2 id="heading-how-to-create-immediately-fulfilled-or-rejected-promises">How to Create Immediately Fulfilled or Rejected Promises</h2>
<p>Sometimes, you may want to wrap a value in a fulfilled Promise. For example, maybe you have an asynchronous function that returns a Promise, but there is a base case where you know the value ahead of time and you don't need to do any asynchronous work.</p>
<p>To do this, you can call <code>Promise.resolve</code> with a value. This returns a Promise that is immediately fulfilled with the value you specified:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'hello'</span>)
  .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">// prints "hello"</span>
  });
</code></pre>
<p>This is more or less equivalent to the following:</p>
<pre><code class="lang-javascript"><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> {
   resolve(<span class="hljs-string">'hello'</span>); 
}).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">// also prints "hello"</span>
});
</code></pre>
<p>To make your API more consistent, you can create an immediately fulfilled Promise and return that in such cases. This way, the code that calls your function knows to always expect a Promise, no matter what.</p>
<p>For example, consider the <code>getUsers</code> function defined earlier. If the array of user IDs is empty, you could simply return an empty array because no users will be loaded.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params">userIds</span>) </span>{
  <span class="hljs-comment">// immediately return the empty array</span>
  <span class="hljs-keyword">if</span> (userIds.length === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.resolve([]);
  }

  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.allSettled(userIds.map(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> getUser(id)))
    .then(<span class="hljs-function"><span class="hljs-params">results</span> =&gt;</span> {
      <span class="hljs-keyword">return</span> results
        .filter(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.status === <span class="hljs-string">'fulfilled'</span>)
        .map(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.value);
    });
}
</code></pre>
<p>Another use for <code>Promise.resolve</code> is to handle the case where you are given a value that may or may not be a Promise, but you want to always treat it as a Promise. </p>
<p>You can safely call <code>Promise.resolve</code> on any value. If it was already a Promise, you'll just get another Promise that will have the same fulfillment or rejection value. If it was not a Promise, it will be wrapped in an immediately fulfilled Promise.</p>
<p>The benefit of this approach is you don't have to do something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getResult</span>(<span class="hljs-params">result</span>) </span>{
  <span class="hljs-keyword">if</span> (result.then) {
     result.then(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
         <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Result:'</span>, value);
     });
  } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Result:'</span>, result);
  }
}
</code></pre>
<p>Similarly, you can create an immediately rejected Promise with <code>Promise.reject</code>. Returning once again to the <code>getUsers</code> function, maybe we want to immediately reject if the user ID array is <code>null</code>, <code>undefined</code>, or not an array.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params">userIds</span>) </span>{
  <span class="hljs-keyword">if</span> (userIds == <span class="hljs-literal">null</span> || !<span class="hljs-built_in">Array</span>.isArray(userIds)) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'User IDs must be an array'</span>));
  }

  <span class="hljs-comment">// immediately return the empty array</span>
  <span class="hljs-keyword">if</span> (userIds.length === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.resolve([]);
  }

  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.allSettled(userIds.map(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> getUser(id)))
    .then(<span class="hljs-function"><span class="hljs-params">results</span> =&gt;</span> {
      <span class="hljs-keyword">return</span> results
        .filter(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.status === <span class="hljs-string">'fulfilled'</span>)
        .map(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.value);
    });
}
</code></pre>
<h3 id="heading-how-to-use-promiserace">How to use <code>Promise.race</code></h3>
<p>Just like <code>Promise.all</code> or <code>Promise.allSettled</code>, the <code>Promise.race</code> static method takes an array of Promises, and returns a new Promise. As the name implies, though, it works somewhat differently.</p>
<p>The Promise returned by <code>Promise.race</code> will wait until the first of the given Promises is fulfilled or rejected, and then that Promise will also be fulfilled or rejected, with the same value. When this happens, the fulfilled or rejected values of the other Promises are lost.</p>
<h3 id="heading-how-to-use-promiseany">How to use <code>Promise.any</code></h3>
<p><code>Promise.any</code> works similarly to <code>Promise.race</code> with one key difference – where <code>Promise.race</code> will be done as soon as any Promise is fulfilled or rejected, <code>Promise.any</code> waits for the first <em>fulfilled</em> Promise.</p>
<h2 id="heading-how-to-use-async-and-await">How to Use <code>async</code> and <code>await</code></h2>
<p><code>async</code> and <code>await</code> are special keywords that simplify working with Promises. They remove the need for callback functions and calls to <code>then</code> or <code>catch</code>. They work with try-catch blocks, as well.</p>
<p>Here's how it works. Instead of calling <code>then</code> on a Promise, you <code>await</code> it by putting the <code>await</code> keyword before it. This effectively "pauses" execution of the function until the Promise is fulfilled.</p>
<p>Here's an example using standard Promises:</p>
<pre><code class="lang-javascript">getUsers().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">'Got users:'</span>, users);
});
</code></pre>
<p>Here's the equivalent code using the <code>await</code> keyword:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> users = <span class="hljs-keyword">await</span> getUsers();
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Got users:'</span>, users);
</code></pre>
<p>Promise chains are a little cleaner, too:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> readFile(<span class="hljs-string">'sourceData.json'</span>);
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> processData(data);
<span class="hljs-keyword">await</span> writeFile(result, <span class="hljs-string">'processedData.json'</span>);
</code></pre>
<p>Remember that each usage of <code>await</code> will pause execution of the rest of the function until the Promise you are awaiting becomes fulfilled. If you want to await several Promises that run in parallel, you can use <code>Promise.all</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> users = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all([getUser(<span class="hljs-number">1</span>), getUser(<span class="hljs-number">2</span>), getUser(<span class="hljs-number">3</span>)]);
</code></pre>
<p>To use the <code>await</code> keyword, your function must be marked as an async function. You can do this by placing the <code>async</code> keyword before your 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">processData</span>(<span class="hljs-params">sourceFile, outputFile</span>) </span>{
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> readFile(sourceFile);
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> processData(data);
  writeFile(result, outputFile);
}
</code></pre>
<p>Adding the <code>async</code> keyword also has another important effect on the function. Async functions always implicitly return a Promise. If you return a value from an async function, the function will actually return a Promise that is fulfilled with that value.</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">add</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;   
}

add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>).then(<span class="hljs-function"><span class="hljs-params">sum</span> =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Sum is:'</span>, sum); 
});
</code></pre>
<p>In the above example, the function is returning the sum of the two arguments <code>a</code> and <code>b</code>. But since it's an <code>async</code> function, it doesn't return the sum but rather a Promise that is fulfilled with the sum.</p>
<h3 id="heading-error-handling-with-async-and-await">Error handling with <code>async</code> and <code>await</code></h3>
<p>We use <code>await</code> to wait for Promise to be fulfilled, but what about handling errors? If you are awaiting a Promise, and it is rejected, an error will be thrown. This means to handle the error, you can put it in a try-catch block:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> readFile(sourceFile);
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> processData(data);
    <span class="hljs-keyword">await</span> writeFile(result, outputFile);
} <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error occurred while processing:'</span>, error);
}
</code></pre>
<h2 id="heading-promise-anti-patterns">Promise Anti-Patterns</h2>
<h3 id="heading-unnecessarily-creating-a-new-promise">Unnecessarily creating a new Promise</h3>
<p>Sometimes there's no getting around creating a new Promise. But if you are already working with Promises returned by an API, you usually shouldn't need to create your own Promise:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</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> {
     fetch(<span class="hljs-string">'https://example.com/api/users'</span>)
       .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json())
       .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> resolve(data))
  });
}
</code></pre>
<p>In this example, we're creating a new Promise to wrap the Fetch API, which already returns Promises. This is unnecessary. Instead, just return the Promise chain from the Fetch API directly:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">'https://example.com/api/users'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json());
}
</code></pre>
<p>In both cases, the code calling <code>getUsers</code> looks the same:</p>
<pre><code class="lang-javascript">getUsers()
  .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">'Got 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 fetching users:'</span>, error));
</code></pre>
<h3 id="heading-swallowing-errors">Swallowing errors</h3>
<p>Consider this version of a <code>getUsers</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">'https://example.com/api/users'</span>)
        .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json())
        .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 loading users:'</span>, error));
}
</code></pre>
<p>Error handling is good, right? You might be surprised by the result if we call this <code>getUsers</code> function:</p>
<pre><code class="lang-javascript">getUsers()
  .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">'Got 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>You might expect this to print "error", but it will actually print "Got users: undefined". This is because the <code>catch</code> call "swallows" the error and returns a new Promise that is fulfilled with the return value of the <code>catch</code> callback, which is <code>undefined</code> (<code>console.error</code> returns <code>undefined</code>). You'll still see the "Error loading users" log message from <code>getUsers</code>, but the returned Promise will be fulfilled, not rejected.</p>
<p>If you want to catch the error inside the <code>getUsers</code> function and still reject the returned Promise, the <code>catch</code> handler needs to return a rejected Promise. You can do this by using <code>Promise.reject</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">'https://example.com/api/users'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json())
    .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 loading users:'</span>, error);
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(error);
    });
}
</code></pre>
<p>Now you'll still get the "Error loading users" message, but the returned Promise will also be rejected with the error.</p>
<h3 id="heading-nesting-promises">Nesting Promises</h3>
<p>Avoid nesting Promise code. Instead, try to use flattened Promise chains.</p>
<p>Instead of this:</p>
<pre><code class="lang-javascript">readFile(sourceFile)
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    processData(data)
      .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
        writeFile(result, outputFile)
          .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'done'</span>);
      });
  });
</code></pre>
<p>Do this:</p>
<pre><code class="lang-javascript">readFile(sourceFile)
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> processData(data))
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> writeFile(result, outputFile))
  .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'done'</span>));
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>Here are the key points for working with Promises:</p>
<ul>
<li>A Promise can be pending, fulfilled, or rejected</li>
<li>A Promise is settled if it is either fulfilled or rejected</li>
<li>Use <code>then</code> to get the fulfilled value of a Promise</li>
<li>Use <code>catch</code> to handle errors</li>
<li>Use <code>finally</code> to perform cleanup logic that you need in either the success or error case</li>
<li>Chain Promises together to perform asynchronous tasks in sequence</li>
<li>Use <code>Promise.all</code> to get a Promise that is fulfilled when all given Promises are fulfilled, or rejects when one of those Promises rejects</li>
<li>Use <code>Promise.allSettled</code> to get a Promise that is fulfilled when all given Promises are either fulfilled or rejected</li>
<li>Use <code>Promise.race</code> to get a Promise that is fulfilled or rejected when the first of the given Promises is either fulfilled or rejected</li>
<li>Use <code>Promise.any</code> to get a Promise that is fulfilled when the first of the given Promises is fulfilled</li>
<li>Use the <code>await</code> keyword to wait for the fulfillment value of a Promise</li>
<li>Use a try-catch block to handle errors when using the <code>await</code> keyword</li>
<li>A function that uses <code>await</code> inside of it must use the <code>async</code> keyword</li>
</ul>
<p>Thank you for reading this deep dive on Promises. I hope you learned something new!</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[ Asynchronous JavaScript – How to Use Promises in Your JS Code ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is a versatile programming language that powers the dynamic behavior of websites.  As web applications become more sophisticated, the need to handle asynchronous operations efficiently becomes crucial. Asynchronous JavaScript allows you to... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-promises-in-javascript/</link>
                <guid isPermaLink="false">66c4c3e5e486f65d4125b7ff</guid>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Mon, 11 Dec 2023 21:52:05 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/Orange-and-white-modern-creative-marketing-plan-Presentation-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is a versatile programming language that powers the dynamic behavior of websites. </p>
<p>As web applications become more sophisticated, the need to handle asynchronous operations efficiently becomes crucial. Asynchronous JavaScript allows you to execute code without blocking the main thread, ensuring a smoother user experience. </p>
<p>Promises are a powerful tool in JavaScript for managing asynchronous operations, providing a cleaner and more organized approach to handling asynchronous code.</p>
<p>Here's what we'll cover:</p>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-asynchronous-javascript">What is asynchronous JavaScript?</a></li>
<li><a class="post-section-overview" href="#heading-the-need-for-promises">The need for promises</a></li>
<li><a class="post-section-overview" href="#heading-what-is-callback-hell">What is callback hell?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-promise">How to create a promise</a></li>
<li><a class="post-section-overview" href="#heading-how-to-consume-promises-with-then-and-catch">How to consume promises with <code>.then()</code> and <code>.catch()</code></a></li>
<li><a class="post-section-overview" href="#heading-how-to-chain-promises-with-then">How to chain promises with <code>.then()</code></a></li>
<li><a class="post-section-overview" href="#heading-more-complex-examples-of-promise-chaining">More complex examples of promise chaining</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-errors-with-catch">How to handle errors with <code>.catch()</code></a></li>
<li><a class="post-section-overview" href="#heading-error-handling-in-more-detail">Error handling in more detail</a></li>
<li><a class="post-section-overview" href="#heading-asyncawait-in-javascript">Async/await in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-alternative-asynchronous-programming-methods">Alternative asynchronous programming methods</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-asynchronous-javascript">What is Asynchronous JavaScript?</h2>
<p>JavaScript is single-threaded, meaning it can only execute one operation at a time. However, in web development, there are tasks that take time to complete, such as fetching data from an API, reading a file, or waiting for a user input. If these tasks were executed synchronously, they would block the main thread, making the user interface unresponsive.</p>
<p>Asynchronous JavaScript allows you to execute code without waiting for the completion of time-consuming tasks. Instead of blocking the main thread, these tasks are delegated to the browser's background processes, and once completed, a callback function is triggered to handle the result.</p>
<h2 id="heading-the-need-for-promises">The Need for Promises</h2>
<p>Before Promises, developers used callbacks to handle asynchronous operations. Callbacks are functions passed as arguments to other functions, and they are executed once the asynchronous operation is completed. </p>
<p>While callbacks serve their purpose, they often lead to a phenomenon known as "callback hell" – a situation where multiple nested callbacks make the code hard to read and maintain.</p>
<p>Callback hell arises when asynchronous operations depend on the results of other asynchronous operations, creating deeply nested callback functions. This can make the code difficult to follow, debug, and maintain. </p>
<p>Promises were introduced to address this issue and provide a more elegant solution to asynchronous code.</p>
<h2 id="heading-what-is-callback-hell">What is Callback Hell?</h2>
<p>Callback hell, also known as the "pyramid of doom," occurs when you have multiple nested callbacks within your code. Each level of nesting represents a subsequent asynchronous operation that depends on the result of the previous one. Here's a simplified example:</p>
<pre><code class="lang-javascript">getData(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) </span>{
  processData(data, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">processedData</span>) </span>{
    updateUI(processedData, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-comment">// More nested callbacks...</span>
    });
  });
});
</code></pre>
<p>As you can see, as the number of asynchronous operations increases, the code indentation deepens, leading to a less readable and maintainable codebase. </p>
<p>Promises provide a way to mitigate callback hell by offering a cleaner and more structured approach to handling asynchronous code.</p>
<h2 id="heading-how-to-create-a-promise">How to Create a Promise</h2>
<p>Let's dive into the basics of creating a promise. The <code>Promise</code> constructor takes a function as its argument, which has two parameters: <code>resolve</code> and <code>reject</code>. These parameters are functions that you call to indicate the completion or failure of the asynchronous operation.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating a Promise that resolves to success</span>
<span class="hljs-keyword">const</span> successPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-comment">// Simulating a successful asynchronous operation</span>
  <span class="hljs-keyword">const</span> success = <span class="hljs-literal">true</span>;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

userPostsPromise = fetchUserPosts();

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

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

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

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

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

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

<span class="hljs-keyword">const</span> dataToSend = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
worker.postMessage(dataToSend);
</code></pre>
<p>In this example, a Web Worker script (<code>worker.js</code>) processes data and sends the result back to the main script. Web Workers are a powerful tool for parallelizing tasks and offloading work from the main thread.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Promises offer a clean and organized way to handle asynchronous code in JavaScript, addressing issues such as callback hell and providing a more readable syntax for asynchronous operations. </p>
<p>By understanding the basics of promises, chaining them together, handling errors, and exploring advanced concepts, you can enhance your ability to write efficient and maintainable asynchronous JavaScript code.</p>
<p>While promises are widely adopted, it's essential to be aware of alternative approaches like async/await and Web Workers, as they may better suit specific use cases or preferences. </p>
<p>As you continue to explore and apply different asynchronous programming methods, you'll be better equipped to build responsive, user-friendly web applications. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How JavaScript Promises Work – Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article, I’m going to teach you one of the most confusing JavaScript topics, which is the Promise object. Promises may seem difficult at first, but they're actually quite simple once you understand how they work. Here's what we'l... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-promise-object-explained/</link>
                <guid isPermaLink="false">66bd918c621c718d60a3106f</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Wed, 29 Nov 2023 15:55:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/js-promise.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article, I’m going to teach you one of the most confusing JavaScript topics, which is the Promise object. Promises may seem difficult at first, but they're actually quite simple once you understand how they work.</p>
<p>Here's what we'll cover:</p>
<ol>
<li><a class="post-section-overview" href="#heading-how-a-promise-works">How a Promise Works</a></li>
<li><a class="post-section-overview" href="#heading-callbacks-vs-promises">Callbacks vs Promises</a></li>
<li><a class="post-section-overview" href="#heading-when-to-use-promises-instead-of-callbacks">When to Use Promises Instead of Callbacks</a></li>
<li><a class="post-section-overview" href="#heading-promises-and-the-fetch-api">Promises and the Fetch API</a></li>
<li><a class="post-section-overview" href="#heading-the-promiseall-method">The <code>Promise.all()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-the-promiseallsettled-method">The <code>Promise.allSettled()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-the-promiseany-method">The <code>Promise.any()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-the-promiserace-method">The <code>Promise.race()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-how-a-promise-works">How a Promise Works</h2>
<p>Basically, a <code>Promise</code> object represents a “pending state” in the most common sense: the promise will eventually be fulfilled at a later date.</p>
<p>To give you an illustration, suppose you want to buy a new phone to replace your old phone, so you open a messaging app to contact a phone store. This is similar to how you access a variable or a function that returns a promise:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/access-a-promise.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration 1: Sending a message to a store is like how you access a Promise object in JavaScript</em></p>
<p>After you send a message explaining what you want, you get an automated message saying that a representative will answer your message shortly. This is similar to receiving a Promise object:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/promise-pending-state.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration 2: An automated message from the store you contacted before. This is the Promise object that you receive in JavaScript</em></p>
<p>A minute later, you get a new message from a human representative, saying that the phone model you want to buy is available for purchase. This is when the Promise was resolved:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/promise-resolved.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration 3: A store representative replied to your message. This is like when a Promise gets resolved</em></p>
<p>Or, in a completely different scenario, the representative tells you that the store doesn’t sell phones, because the store is a food store and not a phone store. This means the Promise was rejected:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/promise-rejected.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration 4: The representative replied that the store doesn't sell phones. This is like when a Promise gets rejected</em></p>
<p>This illustration shows how the <code>Promise</code> object in JavaScript works:</p>
<ul>
<li>A Promise is like the automated message that we saw earlier. It represents a pending state that must be fulfilled at some point later.</li>
<li>The human representative saying that the phone model is available is similar to the <code>resolve()</code> method, which shows that the Promise is fulfilled.</li>
<li>The representative telling you that you’re contacting the wrong store is like the <code>reject()</code> method, which is the method used to show that the Promise can’t be fulfilled because of an error.</li>
</ul>
<p>A typical promise implementation looks like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> p = <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">let</span> isTrue = <span class="hljs-literal">true</span>;
  <span class="hljs-keyword">if</span> (isTrue) {
    resolve(<span class="hljs-string">'Promise resolved'</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">'Promise rejected'</span>);
  }
});
</code></pre>
<p>When creating a new Promise object, we need to pass a callback function that will be called immediately with two arguments: the <code>resolve()</code> and <code>reject()</code> functions.</p>
<p>Depending on the result of the <code>Promise</code>, either the <code>resolve()</code> or the <code>reject()</code> function will be called to end the pending state.</p>
<p>To handle the <code>Promise</code> object, you need to chain the function call with the <code>then()</code> and <code>catch()</code> functions as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> p = <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">let</span> isTrue = <span class="hljs-literal">true</span>;
  <span class="hljs-keyword">if</span> (isTrue) {
    resolve(<span class="hljs-string">'Success'</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">'Error'</span>);
  }
});

p
.then(<span class="hljs-function"><span class="hljs-params">message</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Promise resolved: <span class="hljs-subst">${message}</span>`</span>))
.catch(<span class="hljs-function"><span class="hljs-params">message</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Promise rejected: <span class="hljs-subst">${message}</span>`</span>));
</code></pre>
<p>The <code>resolve()</code> function corresponds to the <code>then()</code> function, while <code>reject()</code> corresponds to the <code>catch()</code> function. You can change the <code>isTrue</code> value to <code>false</code> to test this.</p>
<p>Here’s an illustration of the promise process:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/promise-object--1-.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Process happening inside a Promise. Depending on the code run inside the Promise, it will settle as resolved or rejected.</em></p>
<p>Using the promise pattern, you can call your functions sequentially by placing the next process inside the <code>then()</code> or <code>catch()</code> methods.</p>
<h2 id="heading-callbacks-vs-promises">Callbacks vs Promises</h2>
<p>The promise pattern was created to replace the use of callbacks in certain situations. By using promises, the code we write is more intuitive and maintainable.</p>
<p>Going back to the messaging illustration, let’s create an example of using callbacks to handle the situation. </p>
<p>First, we declare the two variables required for this situation, called <code>isPhoneStore</code> and <code>isPhoneAvailable</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isPhoneStore = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> isPhoneAvailable = <span class="hljs-literal">true</span>;
</code></pre>
<p>Next, we write a function that will process incoming messages. This function will mimic the promise pattern, and it will resolve only when <code>isPhoneStore</code> and <code>isPhoneAvailable</code> are <code>true</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processMessage</span>(<span class="hljs-params">resolveCallback, rejectCallback</span>) </span>{
  <span class="hljs-keyword">if</span> (!isPhoneStore) {
    rejectCallback({
      <span class="hljs-attr">name</span>: <span class="hljs-string">'Wrong store'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'Sorry, this is a food store!'</span>,
    });
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!isPhoneAvailable) {
    rejectCallback({
      <span class="hljs-attr">name</span>: <span class="hljs-string">'Out of stock'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'Sorry, the X phone is out of stock!'</span>,
    });
  } <span class="hljs-keyword">else</span> {
    resolveCallback({
      <span class="hljs-attr">name</span>: <span class="hljs-string">'OK'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'The X phone is available! How many you want to buy?'</span>,
    });
  }
}
</code></pre>
<p>Here, you can see that the function <code>processMessage</code> accepts two callback functions: <code>resolveCallback</code> and <code>rejectCallback</code>.</p>
<p>When we call the function, we need to provide the callback functions, similar to how we need to chain the <code>then()</code> and <code>catch()</code> methods when accessing a promise:</p>
<pre><code class="lang-js">processMessage(
  <span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(value),
  <span class="hljs-function"><span class="hljs-params">reason</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(reason)
);
</code></pre>
<p>In the call to <code>processMessage</code> above, the first argument is the <code>resolveCallback()</code> function, and the second argument is the <code>rejectCallback()</code> function.</p>
<p>If you run the code above, then the <code>resolveCallback()</code> function will be called. You can change one of the two variables to <code>false</code> to trigger the <code>rejectCallback()</code> function.</p>
<p>Now that we have a working callback example, let’s rewrite the code using a promise as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isPhoneStore = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> isPhoneAvailable = <span class="hljs-literal">true</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processMessage</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> (!isPhoneStore) {
      reject({
        <span class="hljs-attr">name</span>: <span class="hljs-string">'Wrong store'</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'Sorry, this is a food store!'</span>,
      });
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!isPhoneAvailable) {
      reject({
        <span class="hljs-attr">name</span>: <span class="hljs-string">'Out of stock'</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'Sorry, the X phone is out of stock!'</span>,
      });
    } <span class="hljs-keyword">else</span> {
      resolve({
        <span class="hljs-attr">name</span>: <span class="hljs-string">'OK'</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'The X phone is available! How many you want to buy?'</span>,
      });
    }
  });
}

processMessage()
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>Here, you can see that the <code>processMessage()</code> function returns a <code>Promise</code> object that gets resolved only when both <code>isPhoneStore</code> and <code>isPhoneAvailable</code> are <code>true</code>.</p>
<p>When one of the two variables is <code>false</code>, then the <code>Promise</code> object will be rejected.</p>
<p>Here you can see that you don’t need to add two extra parameters to the <code>processMessage()</code> function just for the callbacks. Also, when calling the function, you use the <code>then()</code> and <code>catch()</code> methods to handle the result of the promise.</p>
<p>The use of a promise makes the code easier to understand. Here’s the comparison of the two side by side:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/callback-vs-promise.png" alt="Image" width="600" height="400" loading="lazy">
<em>Callbacks vs Promises code comparison</em></p>
<p>I don’t know about you, but I sure love writing and reading the promise pattern more than the callback pattern. 😉</p>
<h3 id="heading-when-to-use-promises-instead-of-callbacks">When to Use Promises Instead of Callbacks</h3>
<p>As I've mentioned before, the promise object is created to replace callback functions in certain situations.</p>
<p>And if you examine the code for the promise object above closely, you'll see that even promises use callbacks inside the <code>then()</code> and <code>catch()</code> methods. This means Promises don't eliminate the need for callbacks.</p>
<p>Promises are used when you need to wait for a certain task to finish before running the next process.</p>
<p>For example, suppose you have three functions that need to run sequentially from one to three.</p>
<p>Each function runs for a few seconds. We simulate this using the <code>setTimeout()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepOne</span>(<span class="hljs-params">value</span>)</span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
  }, <span class="hljs-number">3000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepTwo</span>(<span class="hljs-params">value</span>)</span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
  }, <span class="hljs-number">2000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepThree</span>(<span class="hljs-params">value</span>)</span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
  }, <span class="hljs-number">1000</span>);
}
</code></pre>
<p>Using callbacks, you can define parameters on the <code>stepOne()</code> and <code>stepTwo()</code> functions, then call those functions sequentially like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepOne</span>(<span class="hljs-params">value, callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
    callback();
  }, <span class="hljs-number">3000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepTwo</span>(<span class="hljs-params">value, callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
    callback();
  }, <span class="hljs-number">2000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepThree</span>(<span class="hljs-params">value, callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
    callback();
  }, <span class="hljs-number">1000</span>);
}

<span class="hljs-comment">// Run the functions sequentially with callbacks</span>
stepOne(<span class="hljs-number">1</span>, <span class="hljs-function">() =&gt;</span> {
  stepTwo(<span class="hljs-number">2</span>, <span class="hljs-function">() =&gt;</span> {
    stepThree(<span class="hljs-number">3</span>, <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All steps completed."</span>);
    });
  });
});
</code></pre>
<p>The nested callbacks where you pass the next function inside the previous function is famously known as the "callback hell". This code pattern is hard to read and it's messy.</p>
<p>With promises, you can rewrite the code above as follows:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepOne</span>(<span class="hljs-params">value</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">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(value);
      resolve();
    }, <span class="hljs-number">3000</span>);
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepTwo</span>(<span class="hljs-params">value</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">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(value);
      resolve();
    }, <span class="hljs-number">2000</span>);
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepThree</span>(<span class="hljs-params">value</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">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(value);
      resolve();
    }, <span class="hljs-number">1000</span>);
  });
}

<span class="hljs-comment">// Run the functions sequentially with Promises</span>
stepOne(<span class="hljs-number">1</span>)
  .then(<span class="hljs-function">() =&gt;</span> stepTwo(<span class="hljs-number">2</span>))
  .then(<span class="hljs-function">() =&gt;</span> stepThree(<span class="hljs-number">3</span>))
  .then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All steps completed."</span>);
  });
</code></pre>
<p>Here, you can see that each function returns a promise that resolves when the timeout is finished. The function calls using <code>then()</code> methods maintain a clear order of steps.</p>
<p>In a real-world project where you have many lines of code inside the callback functions, using Promises provides a massive gain in your ability to read, extend, and maintain the code.</p>
<p>But if you're running code that doesn't have to wait for certain processes, then you can use callbacks just fine.</p>
<p>For example, the array methods like <code>forEach()</code> use callbacks, so there's no need for promises there:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];

myArray.forEach(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(value + <span class="hljs-number">5</span>));
</code></pre>
<p>Another use of promises is when you use the Fetch API, which is used to run network requests. Let's see how that works now.</p>
<h2 id="heading-promises-and-the-fetch-api">Promises and the Fetch API</h2>
<p>The Fetch API always returns a <code>Promise</code> object, so you need to handle it using the <code>then()</code> and <code>catch()</code> methods as shown below:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'&lt;Your API URL&gt;'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>If you run a <code>fetch()</code> function and assign the result to a variable, the variable will contain a <code>Promise</code> object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> response = fetch(<span class="hljs-string">'&lt;Your API URL&gt;'</span>);
<span class="hljs-built_in">console</span>.log(response); <span class="hljs-comment">// Promise {&lt;pending&gt;}</span>
</code></pre>
<p>As you can see, the <code>Promise</code> object is assigned to the <code>response</code> variable in a pending state. If you wait a while and then log the object again, the output will be fulfilled:</p>
<pre><code class="lang-txt">Promise {&lt;fulfilled&gt;: Response}
</code></pre>
<p>The Fetch API will return a <code>Response</code> object when the promise is fulfilled. This is also why I usually name the parameter inside the <code>then()</code> method as <code>response</code> . Feel free to name the response as <code>message</code> , <code>value</code> , or anything your team agreed on.</p>
<p>Now that you’ve learned how the <code>Promise</code> object works, it’s time to learn some extra methods related to this object.</p>
<h3 id="heading-the-promiseall-method">The <code>Promise.all()</code> method</h3>
<p>More than just replacing the callback pattern, JavaScript also provides some methods that you can use to work with <code>Promise</code> objects. For example, suppose you deal with three different promises in your project like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Success'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);
</code></pre>
<p>Now, suppose you need all three promises to resolve before moving to the next step. Knowing what we know about promises, we can chain the promises using the <code>then()</code> method like this:</p>
<pre><code class="lang-js">p1.then(<span class="hljs-function"><span class="hljs-params">message1</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> p2.then(<span class="hljs-function"><span class="hljs-params">message2</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> p3.then(<span class="hljs-function"><span class="hljs-params">message3</span> =&gt;</span> {
      <span class="hljs-keyword">return</span> [message1, message2, message3];
    });
  });
}).then(<span class="hljs-function"><span class="hljs-params">messages</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(messages);
});
</code></pre>
<p>In this example, each <code>then()</code> method returns another promise, creating nested callbacks. When the <code>p3</code> promise is resolved, the messages are returned as a single array.</p>
<p>The last <code>then()</code> method would then log the <code>messages</code> array returned by the promises. This approach works, but this is exactly the type of code we want to avoid when using promises.</p>
<p>Instead of using nested callbacks, we can use the <code>Promise.all()</code> method instead. See the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">'Error From Promise One'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);

<span class="hljs-built_in">Promise</span>.all([p1, p2, p3])
  .then(<span class="hljs-function"><span class="hljs-params">messages</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(messages))
  .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>The <code>Promise.all()</code> method accepts an array of promises, and when all promises are resolved, the method will pass the <code>messages</code> returned by the promises as an array and pass it to the <code>then()</code> method.</p>
<p>If one of the promises is rejected, then the method returns the first rejection it encounters and stops any further process.</p>
<p>This method enables you to work with many promises without having to create nested callbacks. You should use this method when you need all promises to resolve.</p>
<h3 id="heading-the-promiseallsettled-method">The <code>Promise.allSettled()</code> method</h3>
<p>The <code>Promise.allSettled()</code> method is similar to the <code>Promise.all()</code> method, but instead of  proceeding to <code>catch()</code> when one of the promises got rejected, the method will store the reject result and continue processing other promises.</p>
<p>When all promises are settled, the method will return an array of objects that contains the details of each promise. For example, suppose you run the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">'Error From Promise One'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);

<span class="hljs-built_in">Promise</span>.allSettled([p1, p2, p3]).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(response);
});
</code></pre>
<p>Then the result would be:</p>
<pre><code class="lang-txt">[
  { status: 'rejected', reason: 'Error From Promise One' },
  { status: 'fulfilled', value: 200 },
  { status: 'fulfilled', value: 'Finished' }
]
</code></pre>
<p>As you can see, the <code>response</code> variable is an array of objects showing the status and the value or reason for that status. When calling this method, you don't need to chain the <code>catch()</code> method.</p>
<p>You should use this method when you always need to know the result of each promise.</p>
<h3 id="heading-the-promiseany-method">The <code>Promise.any()</code> method</h3>
<p>The <code>Promise.any()</code> method is similar to the <code>Promise.all()</code> method, except that it returns only a single value from any promise that calls the <code>resolve()</code> function first. If you try the method as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">'Error From Promise One'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);

<span class="hljs-built_in">Promise</span>.any([p1, p2, p3]).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(response);
});
</code></pre>
<p>The output will be:</p>
<pre><code class="lang-txt">200
</code></pre>
<p>This is because the first promise is rejected, and once the second promise is resolved, the <code>any()</code> method stops any further execution of promises and returns the resolved value.</p>
<p>This method returns an error only when all promises are rejected. You should use this method only when you need to get a single promise resolved out of many promises.</p>
<h3 id="heading-the-promiserace-method">The <code>Promise.race()</code> method</h3>
<p>The <code>Promise.race()</code> method is like the <code>Promise.any()</code> method, with one difference: the promise is settled when any promise is resolved or rejected:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">'Error From Promise One'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);

<span class="hljs-built_in">Promise</span>.race([p1, p2, p3])
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response))
  .catch(<span class="hljs-function"><span class="hljs-params">reason</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(reason));
</code></pre>
<p>Since <code>p1</code> returns a rejection, then the <code>Promise.race()</code> method returns the rejection instead of continuing the process:</p>
<pre><code class="lang-txt">Error From Promise One
</code></pre>
<p>You should use this method only when you need to get a single promise to settle, no matter if the result is resolved or rejected.</p>
<p>As you can see, these four methods of the <code>Promise</code> object provides you with a powerful composition tool that helps you decide how to handle multiple promises in your project.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And now you’ve learned how the <code>Promise</code> object works in JavaScript. A promise is easy to understand when you grasp the three states that can be generated by the promise: pending, resolved, and rejected.</p>
<p>You’ve also learned how promises can be used to replace callbacks, when to use promises instead of callbacks, and how to use promise methods when you need to handle many promises in your project.</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[ How to Use Promise.allSettled() in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever worked with promises in JavaScript and gotten frustrated when one rejects and ruins everything?  You write some promise-based code, everything is chugging along nicely, and then boom – one little promise rejects and the whole chain come... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-promise-allsettled-in-javascript/</link>
                <guid isPermaLink="false">66c861a251f56da58aee7b7a</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rahul ]]>
                </dc:creator>
                <pubDate>Tue, 27 Jun 2023 17:03:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/andrew-petrov-hopnkQoC0dg-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever worked with promises in JavaScript and gotten frustrated when one rejects and ruins everything? </p>
<p>You write some promise-based code, everything is chugging along nicely, and then boom – one little promise rejects and the whole chain comes crashing down.</p>
<p>Your code grinds to a halt and you're left wondering why JavaScript couldn't just ignore that one little hiccup and continue on its merry way. Well, friend, do I have good news for you.</p>
<p>Meet <code>Promise.allSettled()</code>, your new best friend and the promise you never knew you needed. <code>Promise.allSettled()</code> is a game-changer, allowing you to wait for all your promises to settle – either resolve or reject – and then take action based on the results.</p>
<p>No more ruined promise chains or unhandled rejections. Just pure, unadulterated promise bliss. Join me as we dive into this little-known but incredibly useful promise method and see just how much it can simplify your <a target="_blank" href="https://www.freecodecamp.org/news/asynchronous-javascript/">asynchronous JavaScript</a> code.</p>
<h2 id="heading-what-is-promiseallsettled">What Is Promise.allSettled()?</h2>
<p>So you want to use JavaScript's Promise.allSettled() method, but aren't quite sure how it works or why you'd want to use it? No worries, I've got you covered.</p>
<p><code>Promise.allSettled()</code> waits for all promises you give it to settle, meaning either resolve or reject. It then returns an array of objects with the status and value or reason for each promise. </p>
<p>This is useful when you have multiple asynchronous tasks that you want to ensure have completed, but don't necessarily care if some fail.</p>
<p>For example, say you have three API calls that return promises, and you want to get all the data back from the successful calls, even if one fails. You could do:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.allSettled([apiCall1(), apiCall2(), apiCall3()]).then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> {});
</code></pre>
<p>This will run all three API calls, and the <code>.then()</code> callback will be called once they have all settled. The results array will have three objects: one for each promise, with either a status of 'fulfilled' and the data, or 'rejected' and the error. </p>
<p>We can filter to just get the successful calls, and proceed using that data.</p>
<p>The key things to remember are:</p>
<ul>
<li><code>Promise.allSettled()</code> waits for all input promises to settle and returns their outcomes.</li>
<li>Settled means either resolved (fulfilled) or rejected.</li>
<li>It returns an array of objects with status and value/reason for each input promise.</li>
<li>It allows handling successful promises even when some reject.</li>
</ul>
<h2 id="heading-the-problem-with-promiseall-and-the-solution-with-promiseallsettled">The problem with <code>Promise.all()</code> and the solution with <code>Promise.allSettled()</code></h2>
<p><code>Promise.all()</code> is great when you want to wait for multiple promises to complete and get an array of all the resolved values. But it has one major downside: if any of the promises reject, the entire <code>Promise.all()</code> rejects immediately.</p>
<p>This can be problematic in some cases. For example, say you make requests to three different backend services, and you don't really care if one fails as long as the other two succeed. With <code>Promise.all()</code>, a single rejected promise would reject the entire group, and you'd miss the successful responses from the other promises.</p>
<p>Fortunately, there's a simple solution: <code>Promise.allSettled()</code>. This works similarly to <code>Promise.all()</code> but instead of rejecting immediately if any promise rejects, it waits for all promises to settle (either resolve or reject) and then returns an array of objects with the status and value/reason for each promise.</p>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.allSettled([
  <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">1</span>),
  <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"2"</span>)),
  <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">3</span>),
]).then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> {
  <span class="hljs-comment">// results is an array of:</span>
  <span class="hljs-comment">// {status: "fulfilled", value: 1}</span>
  <span class="hljs-comment">// {status: "rejected", reason: Error}</span>
  <span class="hljs-comment">// {status: "fulfilled", value: 3}</span>
});
</code></pre>
<p>As you can see, even though the second promise rejected, we still get the resolved values from the other promises. This allows you to handle rejections gracefully without missing any successful responses.</p>
<p><code>Promise.allSettled()</code> provides more flexibility in these types of situations. You get the full picture of all your promises, regardless of some rejecting, so you have the opportunity to still make use of any resolved values and handle rejections appropriately.</p>
<p>So next time you need to wait on multiple promises but can't afford to miss any resolved values due to a rejection, be sure to reach for <code>Promise.allSettled()</code>! It's a very useful addition to the <a target="_blank" href="https://www.freecodecamp.org/news/tag/promises/">Promise API</a>.</p>
<h2 id="heading-common-questions-about-promiseallsettled">Common Questions About <code>Promise.allSettled()</code></h2>
<h3 id="heading-will-promiseallsettled-slow-down-my-code">Will <code>Promise.allSettled()</code> slow down my code?</h3>
<p>Not really. <code>Promise.allSettled()</code> simply waits for all the promises you pass to it to settle, either by fulfilling or rejecting. It doesn’t do anything else that would impact performance.</p>
<h3 id="heading-can-i-still-catch-errors-with-promiseallsettled">Can I still catch errors with <code>Promise.allSettled()</code>?</h3>
<p>Yes, you absolutely can! <code>Promise.allSettled()</code> will give you the outcome of each promise, whether it was fulfilled or rejected. </p>
<p>For any rejected promises, you'll get the reason why it rejected, usually an error. You can catch these errors in the <code>.catch()</code> handler of the <code>Promise.allSettled()</code> call.</p>
<h3 id="heading-when-should-i-use-promiseallsettled-vs-promiseall">When should I use <code>Promise.allSettled()</code> vs <code>Promise.all()</code>?</h3>
<p>Use <code>Promise.allSettled()</code> when you want to run multiple promises in parallel, but don’t want a single rejected promise to cause the entire group to reject. </p>
<p>For example, if you're fetching data from multiple third-party APIs, a rejected promise from one API shouldn’t stop you from getting data from the other APIs.</p>
<p>Use <code>Promise.all()</code> when you want to run promises in parallel but need them all to successfully complete for your code to continue. </p>
<p>For example, if you need to fetch data from two APIs to display on a page, you’d want both promises to fulfill before rendering the data.</p>
<h3 id="heading-can-i-get-the-results-of-the-settled-promises">Can I get the results of the settled promises?</h3>
<p>Yes! <code>Promise.allSettled()</code> returns an array of objects with the status and value/reason for each promise. For example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.allSettled([
  <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">1</span>),
  <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"2"</span>)),
  <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">3</span>),
]).then(<span class="hljs-function">(<span class="hljs-params">results</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(results);
  <span class="hljs-comment">/*
    [
      { status: "fulfilled", value: 1 },
      { status: "rejected", reason: Error: 2 },
      { status: "fulfilled", value: 3 }
    ]
    */</span>
});
</code></pre>
<p>You'll get information on all the promises, whether they fulfilled or rejected, so you have the full picture of the parallel operations.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So there you have it. <code>Promise.allSettled()</code> is a handy method you never knew you needed. </p>
<p>No longer do you have to wrap <code>Promise.all()</code> in a try/catch just to handle potential rejections. You can let <code>Promise.allSettled()</code> handle all that for you and just focus on the resolved values. Your async code will be cleaner and easier to read.</p>
<p>Thank you for reading. I am <a target="_blank" href="https://rahul.biz">Rahul</a>, 19, and a technical writer. Here is my <a target="_blank" href="https://fueler.io/rahoool">proof of work</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Promises Work in JavaScript – A Comprehensive Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ By Amazing Enyichi Agu JavaScript has the ability to carry out asynchronous (or async) instructions. These instructions run in the background until they have finished processing.  Asynchronous instructions do not stop the JavaScript engine from activ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/guide-to-javascript-promises/</link>
                <guid isPermaLink="false">66d45e3d8812486a37369c93</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 13 Jun 2023 16:35:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/promises.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Amazing Enyichi Agu</p>
<p>JavaScript has the ability to carry out asynchronous (or async) instructions. These instructions run in the background until they have finished processing. </p>
<p>Asynchronous instructions do not stop the JavaScript engine from actively accepting and processing more instructions. This is why JavaScript is non-blocking in nature.</p>
<p>There are a few asynchronous features in JavaScript, and one of them is <strong>Promises</strong>. To work with promises, you must adopt a special syntax that makes writing async instructions a lot more organized. Working with promises is a very useful skill every JavaScript developer should learn.</p>
<p>This article is an in-depth guide to promises in JavaScript. You are going to learn why JavaScript has promises, what a promise is, and how to work with it. You are also going to learn how to use async/await—a feature derived from promises—and what a job queue is.</p>
<p>Here are the topics we will cover:</p>
<ol>
<li><a class="post-section-overview" href="#heading-why-should-you-care-about-promises">Why should you care about promises?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-promise">What is a promise?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-promise-in-javascript">How to create a promise in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-how-to-attach-a-callback-to-a-promise">How to attach a callback to a promise</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-errors-in-a-promise">How to handle errors in a promise</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-many-promises-at-once">How to handle many promises at once</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-asyncawait-syntax">What is the async/await syntax?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-an-async-function-in-javascript">How to create an async function in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-await-keyword">How to use the await keyword</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-errors-in-asyncawait">How to handle errors in async/await</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-job-queue">What is a job queue?</a></li>
</ol>
<p>This guide <em>promises</em> to be an interesting and insightful read. :) It is meant for anyone looking to be better at writing JavaScript async instructions, thereby properly utilizing what the language has to offer. With all that out of the way, let's get started.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>In order to follow along with the material and grasp it, here are a few things you should have:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-complete-javascript-handbook-f26b2c71719c/">Basic Knowledge of JavaScript</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/javascript-asynchronous-operations-in-the-browser/">Knowledge of how JavaScript processes async operations</a></li>
</ul>
<p>Knowing these topics will help you properly understand what you are about to learn. If you do not have the prerequisites, you can go learn them and return. The article will use some concepts from those topics here.</p>
<h2 id="heading-why-should-you-care-about-promises">Why Should You Care about Promises?</h2>
<p>Promises were not always part of JavaScript. Callbacks worked together with asynchronous functions to produce desired results in the past. A callback is any function that is a parameter of an async function, which the async function invokes to complete its operation. </p>
<p>To call an async function, you had to pass a callback as an argument like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callback</span>(<span class="hljs-params">result</span>) </span>{
  <span class="hljs-comment">// Use the result from the Async operation</span>
}

randomAsyncOperation(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> callback(response));
</code></pre>
<p>But callbacks had a huge problem. Demonstrating the problem makes understanding it easier. </p>
<p>Assume you had an asynchronous function that fetched data somewhere on the internet. This function should accept two callbacks, <code>successCallback</code> and <code>failureCallback</code>.</p>
<p>The <code>successCallback</code> would run if the operation was successful and the program found the appropriate resource. But the <code>failureCallback</code> would run if the operation was unsuccessful and could not find the resource.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SuccessCallback</span>(<span class="hljs-params">result</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Resource found"</span>, result);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">failureCallback</span>(<span class="hljs-params">error</span>) </span>{
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Ooops. Something went wrong"</span>, error);
}
</code></pre>
<p>To run the async function, you had to pass the two callback functions as arguments:</p>
<pre><code class="lang-js">fetchResource(url, successCallback, failureCallback)
</code></pre>
<p>Here, <code>url</code> is a variable that represents the location of the resource.</p>
<p>This code will run smoothly for now. You've taken care of both possible scenarios the function could run into. You have a callback for a successful operation and a callback for a failed operation.</p>
<p>Now assume you want to perform many other fetch operations, but each operation must be successful for the next one to run. This is useful if the data you need must come in a certain order and cannot be scattered. </p>
<p>For example, you might run into this situation if the result of the next operation depends on the result of the previous one. </p>
<p>In this case, your success callbacks would have their own success callbacks, which is important because you need to use the results if they come in.</p>
<pre><code class="lang-js">fetchResource(
  url,
  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
    <span class="hljs-comment">// Do something with the result</span>
    fetchResource(
      newUrl,
      <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
        <span class="hljs-comment">// Do something with the new result</span>
        fetchResource(
          anotherUrl,
          <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
            <span class="hljs-comment">// Do something with the new result</span>
          },
          failureCallback
        );
      },
      failureCallback
    );
  },
  failureCallback
);
</code></pre>
<p>From the example, you may notice a complication developing. You would have to keep nesting your success callbacks while repeating the <code>failureCallback</code> every time you call the async function. </p>
<p>These nested callbacks led to the <a target="_blank" href="https://medium.com/dsc-srm/javascript-callback-hell-or-pyramid-of-doom-4f786d14b997">‘Callback Pyramid of Doom’</a> or callback hell, which can quickly become a nightmare. Could there be a more efficient way of handling situations like this?</p>
<p>JavaScript introduced Promises as part of <a target="_blank" href="https://262.ecma-international.org/6.0/#sec-promise-constructor">ES6 (ES2015)</a> to solve this problem. It simplified working with callbacks and made for better syntax as you'll see shortly. Promises are now the foundation for most modern asynchronous operations developers use in JavaScript today.</p>
<h2 id="heading-what-is-a-promise">What is a Promise?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/A9vQ.gif" alt="An animated Pinky Promise between two people" width="600" height="400" loading="lazy">
<em>Image Credit: <a target="_blank" href="https://gifer.com/en/Pxwc">https://gifer.com</a></em></p>
<p>A promise is an assurance or guarantee that something will happen in the future. A person can promise another person a specific outcome or result. Promises are not limited to individuals, governments and organizations can also make promises. You have probably made a promise before.</p>
<p>With this assurance (promise) comes two possible outcomes–either fulfillment or failure. A promise is tied to an outcome that will show it is fulfilled. If that outcome does not happen, then the promise failed. A promise at the end must have one of these results.</p>
<p>In JavaScript, a Promise is an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects">object</a> that will produce a single value some time in the future. If the promise is successful, it will produce a resolved value, but if something goes wrong then it will produce a reason why the promise failed. The possible outcomes here are similar to that of promises in real life.</p>
<p>JavaScript promises can be in one of three possible states. These states indicate the progress of the promise. They are:</p>
<ul>
<li><em>pending</em>: This is the default state of a defined promise</li>
<li><em>fulfilled</em>:  This is the state of a successful promise</li>
<li><em>rejected</em>: This is the state of a failed promise</li>
</ul>
<p>A promise goes from <em>pending</em> to <em>fulfilled</em>, or from <em>pending</em> to <em>rejected—</em>‘fulfilled’ and ‘rejected’ indicate the end of a promise. </p>
<p>From now on, this article will refer to a 'promise' as the JavaScript object.</p>
<h2 id="heading-how-to-create-a-promise-in-javascript">How to Create a Promise in JavaScript</h2>
<p>To create a promise, you need to create an instance object using the <code>Promise</code> constructor function. The <code>Promise</code> constructor function takes in one parameter. That parameter is a function that defines when to resolve the new promise, and optionally when to reject it.</p>
<pre><code class="lang-js"><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">// Condition to resolve or reject the promise</span>
});
</code></pre>
<p>For example, assume you want a promise to resolve after a timeout of two seconds. You can achieve this by writing it into the parameter of the constructor function.</p>
<pre><code class="lang-js"><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-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-string">"Done!"</span>), <span class="hljs-number">2000</span>);
});
</code></pre>
<p>In promises, <code>resolve</code> is a function with an optional parameter representing the resolved value. Also, <code>reject</code> is a function with an optional parameter representing the reason why the promise failed. In the example above, the resolved value of the promise is the string <code>'Done!'</code>.</p>
<p>Here is yet another example showing how you can resolve or reject a promise based on the conditions you set. In this example, the outcome of the promise is based on a random number the program generates.</p>
<pre><code class="lang-js"><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-keyword">const</span> num = <span class="hljs-built_in">Math</span>.random();
  <span class="hljs-keyword">if</span> (num &gt;= <span class="hljs-number">0.5</span>) {
    resolve(<span class="hljs-string">"Promise is fulfilled!"</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">"Promise failed!"</span>);
  }
});
</code></pre>
<p>From these examples, you can see that you have control over when to resolve or reject your promise and can tie it to a certain condition. With that, you have learned how to create a promise in JavaScript.</p>
<h2 id="heading-how-to-attach-a-callback-to-a-promise">How to Attach a Callback to a Promise</h2>
<p>To create a callback for a promise, you need to use the <code>.then()</code> method. This method takes in two callback functions. The first function runs if the promise is resolved, while the second function runs if the promise is rejected.</p>
<pre><code class="lang-js"><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-keyword">const</span> num = <span class="hljs-built_in">Math</span>.random();
  <span class="hljs-keyword">if</span> (num &gt;= <span class="hljs-number">0.5</span>) {
    resolve(<span class="hljs-string">"Promise is fulfilled!"</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">"Promise failed!"</span>);
  }
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleResolve</span>(<span class="hljs-params">value</span>) </span>{
  <span class="hljs-built_in">console</span>.log(value);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleReject</span>(<span class="hljs-params">reason</span>) </span>{
  <span class="hljs-built_in">console</span>.error(reason);
}

promise.then(handleResolve, handleReject);
<span class="hljs-comment">// Promise is fulfilled!</span>
<span class="hljs-comment">// or</span>
<span class="hljs-comment">// Promise failed!</span>
</code></pre>
<p>That is the way to handle the possible outcomes of your promise. Any unhandled errors in your promise will keep them in a rejected state at the end but handled errors makes the operation return a fulfilled promise.</p>
<p>It is possible to create an immediately resolved promise, and then attach a callback with the <code>.then()</code> method. You can also create an immediately rejected promise in the same way too.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"Successful"</span>).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">// Successful</span>

<span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">"Not successful"</span>).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">// Error: Uncaught (in promise)</span>
</code></pre>
<p>The error in the rejected promise is because you need to define a separate callback to handle a rejected promise.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">"Not successful"</span>).then(
  <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">/*Empty Callback if Promise is fulfilled*/</span>
  },
  <span class="hljs-function">(<span class="hljs-params">reason</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(reason)
);
<span class="hljs-comment">// Not Successful</span>
</code></pre>
<p>Now you have properly handled a rejected outcome.</p>
<p>Promises make it incredibly easy to chain asynchronous instructions. When you handle a promise with the <strong><code>.then()</code></strong> method, the operation always returns another promise. By employing this approach, you can eliminate the previously mentioned 'Callback Pyramid of Doom'. </p>
<p>Consider the code that previously caused the pyramid structure:</p>
<pre><code class="lang-js">fetchResource(
  url,
  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
    <span class="hljs-comment">// Do something with the result</span>
    fetchResource(
      newUrl,
      <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
        <span class="hljs-comment">// Do something with the new result</span>
        fetchResource(
          anotherUrl,
          <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
            <span class="hljs-comment">// Do something with the new result</span>
          },
          failureCallback
        );
      },
      failureCallback
    );
  },
  failureCallback
);
</code></pre>
<p>However, because <code>.then()</code> returns another promise, this is how to write the same instructions above with promises:</p>
<pre><code class="lang-js">fetchResource(url)
  .then(handleResult, failureCallback)
  .then(handleNewResult, failureCallback)
  .then(handleAnotherResult, failureCallback);
</code></pre>
<p>As you can see, calling promises does not require a nested syntax. You can even eliminate the repeated <code>failureCallback</code> to make the code a lot neater, which is something the upcoming section of the article will explore.</p>
<h2 id="heading-how-to-handle-errors-in-a-promise">How to Handle Errors in a Promise</h2>
<p>To handle errors in Promises, use the <code>.catch()</code> method. If anything goes wrong with any of your promises, this method can catch the reason for that error.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>()).catch(<span class="hljs-function">(<span class="hljs-params">reason</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(reason));
<span class="hljs-comment">// Error</span>
</code></pre>
<p>This time in our example, the error output is no longer ‘uncaught’ because of <code>.catch()</code>.</p>
<p>You can also use the <code>.catch()</code> method in a chain of promises. It catches the first error it encounters in the chain. </p>
<p>For instance, refactoring the chain of promises following the <code>fetchResource()</code> function from the example of the previous section. This how you can stop error callback repetition in your code.</p>
<pre><code class="lang-js">fetchResource(url)
  .then(handleResult)
  .then(handleNewResult)
  .then(handleAnotherResult)
  .catch(failureCallback);
</code></pre>
<p>You can also use <code>.catch()</code> to check for errors in a group of promises before proceeding with further asynchronous operations.</p>
<pre><code class="lang-js">fetchResource(url)
  .then(handleResult)
  .then(handleNewResult)
  .catch(failureCallback)
  <span class="hljs-comment">// Check for Errors in the above group of promises before proceeding</span>
  .then(handleAnotherResult);
</code></pre>
<p>The <strong><code>.catch()</code></strong> method addresses any errors in a promise without requiring the nesting of error callback functions.</p>
<p>To chain an asynchronous operation to a promise regardless of if the promise is resolved or not, use the <code>.finally()</code> method. The <code>.then()</code> method is how you handle the results of a promise writing individual conditions for both resolved and rejected. <code>.catch()</code> runs only when there is an error. But sometimes you might want an operation to run no matter what happens to earlier promises. </p>
<p>Using <code>finally()</code> helps prevent possible code repetition in <code>.then()</code> and <code>.catch()</code>. It is for operations you must run whether there is an error or not.</p>
<pre><code class="lang-js">fetchResource(url)
  .then(handleResult)
  .then(handleNewResult)
  .finally(onFinallyHandle);
</code></pre>
<p>The <code>finally()</code> method has a few use cases in real-world applications. It is important if you want to perform cleanup operations for activities the promise initiated. Another use case—on Front-End Web Applications—is making user interface updates like stopping a loading spinner.</p>
<h2 id="heading-how-to-handle-many-promises-at-once">How to Handle Many Promises at Once</h2>
<p>It is possible to run more than one promise at a time. All the examples you have seen so far are for promises that run one after the other. </p>
<p>In the previous examples, promises run similarly to synchronous code in the sense that they wait for the previous one to be resolved or rejected. But you could have multiple promises that run in parallel.</p>
<p>Here are the available methods that can help us achieve this:</p>
<ul>
<li><code>Promise.all()</code></li>
<li><code>Promise.race()</code></li>
<li><code>Promise.any()</code></li>
<li><code>Promise.allSettled()</code></li>
</ul>
<p>In this section of the article, we'll review these methods.</p>
<h3 id="heading-the-promiseall-method">The <code>Promise.all()</code> method</h3>
<p><strong><code>Promise.all()</code></strong> accepts an array of promises as an argument but returns a single promise as the output. The single promise it returns resolves with an array of values if all the promises in the input array are fulfilled. The array <code>Promise.all()</code> resolves with will contain the resolve values of individual promises in the input array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise1 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">`First Promise's Value`</span>);
<span class="hljs-keyword">const</span> promise2 = <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">3000</span>, <span class="hljs-string">`Second Promise's Value`</span>)
);
<span class="hljs-keyword">const</span> promise3 = <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">2000</span>, <span class="hljs-string">`Third Promise's Value`</span>)
);

<span class="hljs-built_in">Promise</span>.all([promise1, promise2, promise3]);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *Promise {&lt;fulfilled&gt;: Array(3)}*</span>

<span class="hljs-built_in">Promise</span>.all([promise1, promise2, promise3]).then(<span class="hljs-function">(<span class="hljs-params">values</span>) =&gt;</span> {
  values.forEach(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(value));
});

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// First Promise's Value</span>
<span class="hljs-comment">// Second Promise's Value</span>
<span class="hljs-comment">// Third Promise's Value</span>
</code></pre>
<p>If at least one promise in the input array does not resolve, <code>Promise.all()</code> will return a rejected promise with a reason. The reason for the rejection will be the same as that of the first rejected promise in the input array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise1 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">`First Promise's Value`</span>);
<span class="hljs-keyword">const</span> promise2 = <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>(reject, <span class="hljs-number">2000</span>, <span class="hljs-string">`First reason for rejection`</span>)
);
<span class="hljs-keyword">const</span> promise3 = <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>(reject, <span class="hljs-number">3000</span>, <span class="hljs-string">`Second reason for rejection`</span>)
);

<span class="hljs-built_in">Promise</span>.all([promise1, promise2, promise3]);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *Promise {&lt;rejected&gt;: "First reason for rejection"}*</span>
</code></pre>
<p><code>Promise.all()</code> will run all the input promises before it returns a value. But it does not run the promises one after the other–instead it runs them at the same time. </p>
<p>This is why the total time it would take <code>Promise.all()</code> to return a value is roughly the time it would take the longest promise in the array to finish. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/quickpoll.png" alt="Illustration showing when Promise.all() will produce a value" width="600" height="400" loading="lazy"></p>
<p>Despite that, it has to finish running <em>all</em> the promises before it returns anything.</p>
<h3 id="heading-the-promiserace-method">The <code>Promise.race()</code> method</h3>
<p><code>Promise.race()</code> accepts an array of promises as an argument and returns a single promise as an output. The single promise it returns is the fastest promise to finish running—resolved or not. This means <code>Promise.race()</code> will return the promise with the shortest execution time in an array of promises.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span>
  <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">3000</span>, <span class="hljs-string">`First Promise's Value`</span>)
);
<span class="hljs-keyword">const</span> promise2 = <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">2000</span>, <span class="hljs-string">`Second Promise's Value`</span>)
);
<span class="hljs-keyword">const</span> promise3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">`Third Promise's Value`</span>);

<span class="hljs-built_in">Promise</span>.race([promise1, promise2, promise3]);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *Promise {&lt;fulfilled&gt;: "Third Promise's Value"}*</span>
</code></pre>
<p>In the example above, because <code>promise3</code> is a promise that resolves on being created, <code>Promise.race()</code> returns it as the fastest. Just like other <code>Promise</code> methods the article discusses in this section, it runs the promises in parallel and not one after the other.</p>
<p>If the promise with the shortest execution time happens to be rejected with a reason, <code>Promise.race()</code> returns a rejected promise and the reason why the fastest promise was rejected.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise1 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">`Reason for rejection`</span>);
<span class="hljs-keyword">const</span> promise2 = <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">3000</span>, <span class="hljs-string">`First resolved Promise`</span>)
);
<span class="hljs-keyword">const</span> promise3 = <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">2000</span>, <span class="hljs-string">`Second resolved Promise`</span>)
);

<span class="hljs-built_in">Promise</span>.race([promise1, promise2, promise3]);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *Promise {&lt;rejected&gt;: "Reason for rejection"}*</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/quickpoll--3-.png" alt="Illustration showing when Promise.race() will produce a value" width="600" height="400" loading="lazy"></p>
<p><code>Promise.race()</code> is useful for running a list of asynchronous operations but only needing the result of the fastest executed operation.</p>
<h3 id="heading-the-promiseany-method">The <code>Promise.any()</code> method</h3>
<p><code>Promise.any()</code> accepts an array of Promises as an argument but returns a single Promise as the output. The single promise it returns is the first resolved promise in the input array. This method waits for <em>any</em> promise in the array to be resolved and would immediately return it as the output.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span>
  <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">3000</span>, <span class="hljs-string">`First Promise's Value`</span>)
);
<span class="hljs-keyword">const</span> promise2 = <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">2000</span>, <span class="hljs-string">`Second Promise's Value`</span>)
);
<span class="hljs-keyword">const</span> promise3 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">`Third Promise's Value`</span>);

<span class="hljs-built_in">Promise</span>.any([promise1, promise2, promise3]);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *Promise {&lt;fulfilled&gt;: "Second Promise's Value"}*</span>
</code></pre>
<p>From the above example, <code>promise1</code> will resolve after 3 seconds, <code>promise2</code> will resolve after 2 seconds, and <code>promise3</code> immediately rejects. Because <code>Promise.any()</code> is looking for the first successful promise, it returns <code>promise2</code>. <code>promise1</code> is a little bit late and so it's left behind.</p>
<p>If none of the promises in the array are resolved, <strong><code>Promise.any()</code></strong> returns a rejected promise. This rejected promise contains a JavaScript array of reasons, where each reason corresponds with that of a promise from the input array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise1 = <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>(reject, <span class="hljs-number">3000</span>, <span class="hljs-string">`First rejection reason`</span>)
);
<span class="hljs-keyword">const</span> promise2 = <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>(reject, <span class="hljs-number">2000</span>, <span class="hljs-string">`Second rejection reason`</span>)
);
<span class="hljs-keyword">const</span> promise3 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">`Third rejection reason`</span>);

<span class="hljs-built_in">Promise</span>.any([promise1, promise2, promise3]);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *Promise {&lt;rejected&gt;: Aggregate Error: All Promises were rejected}*</span>

<span class="hljs-built_in">Promise</span>.any([promise1, promise2, promise3]).catch(<span class="hljs-function">(<span class="hljs-params">{ errors }</span>) =&gt;</span>
  <span class="hljs-built_in">console</span>.log(errors)
);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *(3) ["First* rejection reason*", "Second* rejection reason*", "Third* rejection reason*"]*</span>
</code></pre>
<p>This method is useful for asynchronous operations where the fastest successful promise is all you need. <code>Promise.any()</code> and <code>Promise.race()</code> are similar, except that <code>Promise.any()</code> will return the fastest promise to complete and be resolved, while <code>Promise.race()</code> will return the fastest promise to complete and does not care if it is resolved or not.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/quickpoll--1-.png" alt="Illustration showing when Promise.any() will produce a value" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-promiseallsettled-method">The <code>Promise.allSettled()</code> method</h3>
<p><code>Promise.allSettled()</code> became a feature of JavaScript promises with the release of <a target="_blank" href="https://262.ecma-international.org/11.0/">ES2020</a>. It handles promises in parallel just like the other promise methods the article discusses in this section. </p>
<p><code>Promise.allSettled()</code> helps to write more efficient asynchronous code as it shows the outcome of all the promises in the array regardless of the status—resolved or rejected.</p>
<p><code>Promise.allSettled()</code> accepts an array of promises as an argument and returns a single promise as the output. </p>
<p>The single promise it returns will always resolve or enter the state ‘fulfilled’ after all the input promises are settled. It does not care if any individual promise in the input array rejected. The array <code>Promise.all()</code> resolves with will contain the resolve values or rejection reasons of promises in the input array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span>
  <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">3000</span>, <span class="hljs-string">`First Promise's Value`</span>)
);
<span class="hljs-keyword">const</span> promise2 = <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">2000</span>, <span class="hljs-string">`Second Promise's Value`</span>)
);
<span class="hljs-keyword">const</span> promise3 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">`Third Promise's Value`</span>);

<span class="hljs-built_in">Promise</span>.allSettled([promise1, promise2, promise3]);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *Promise {&lt;fulfilled&gt;: Array(3)}*</span>

<span class="hljs-built_in">Promise</span>.allSettled([promise1, promise2, promise3]).then(<span class="hljs-built_in">console</span>.log);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">/*
(3) [{…}, {…}, {…}]
0: {status: 'fulfilled', value: "First Promise's Value"}
1: {status: 'fulfilled', value: "Second Promise's Value"}
2: {status: 'rejected', reason: "Third Promise's Value"}
*/</span>
</code></pre>
<p>From the example above, you can see that even though <code>promise3</code> rejects on creation, <code>Promise.allSettled()</code> still returned a ‘fulfilled’ promise. It does this even if all the promises in the input array reject.</p>
<p><code>Promise.allSettled()</code> is similar to <code>Promise.all()</code> in that all their input promises must settle before the promise they return has a settled state—fulfilled or rejected. </p>
<p>The difference is <code>Promise.all()</code> can only be successful if all the promises in the input are resolved, while <code>Promise.allSettled()</code> does not care about the status of the input promises.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/quickpoll--2-.png" alt="Illustration showing when Promise.allSettled() will produce a value" width="600" height="400" loading="lazy"></p>
<p>Using this method will give you an overview of how all your promises did, the ones that were resolved and the ones that were rejected. It gives complete information on all the promises you pass into it and allows you to examine them independently—the outcome of one does not affect the state of the promise the method returns.</p>
<h2 id="heading-what-is-the-asyncawait-syntax">What is the Async/Await Syntax?</h2>
<p>Async/await syntax became a feature of JavaScript with the release of <a target="_blank" href="https://262.ecma-international.org/8.0/">ES8(ES2017)</a>. It is built on top of promises, and you can see it as an alternative syntax to promises. </p>
<p><code>async/await</code> eliminates the chaining that is common with the promises syntax, and ends up making asynchronous code look a lot more synchronous.</p>
<p>Promises are an excellent way to avoid the previously discussed ‘Callback Pyramid of Doom’, but async/await takes asynchronous code further. With async/await, code is easier to follow and maintain. It came about as a way to improve code readability for asynchronous operations. It is the modern way of using promises.</p>
<h2 id="heading-how-to-create-an-async-function-in-javascript">How to Create an Async Function in JavaScript</h2>
<p><code>async</code> is a JavaScript keyword used to create a function. The function this keyword helps create will always return a promise. To use it, place <code>async</code> before the <code>function</code> keyword when declaring the function.</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">example</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Return a value</span>
}

example()

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *Promise {&lt;fulfilled&gt;: undefined}*</span>
</code></pre>
<p>From the code example, you can see that the function returns a promise with a value <code>undefined</code>. This is because anything the <code>async</code> function returns will be the resolved value of the resulting promise. In this case, the function does not return anything, hence <code>undefined</code>.</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">example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Feels good to be an async function"</span>;
}

example();

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// *Promise {&lt;fulfilled&gt;: "Feels good to be an async function"}*</span>
</code></pre>
<p>In the above example, the function returns a string, which becomes the resolved value of the resulting promise. That is the way to create an <code>async</code> function.</p>
<h2 id="heading-how-to-use-the-await-keyword">How to Use the Await Keyword</h2>
<p>To use the <code>await</code> keyword, place it before a promise. It is an indicator for the <code>async</code> function to pause execution until that promise is settled. </p>
<p>It is similar to the <code>.then()</code> method which makes sure a promise is ‘fulfilled’ or ‘rejected’ before it continues. Note that you can only use the <code>await</code> keyword inside an <code>async</code> function.</p>
<p>Instead of chaining promises with <code>.then()</code> as the article earlier teaches, you can repeatedly <em>await</em> the asynchronous operations making your code cleaner and easier to read.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> timerPromise = <span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</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">3000</span>, message));

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">asyncFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> timerPromise(<span class="hljs-string">"promise finished!"</span>);
  <span class="hljs-built_in">console</span>.log(result);
}

<span class="hljs-comment">// Output on the Console after 3 seconds</span>

<span class="hljs-comment">// promise finished!</span>
</code></pre>
<p>Using the <code>await</code> keyword before a promise will produce the resolved value of that promise. It is evident from the line <code>const result = await promise('promise finished!')</code> where  <code>result</code> becomes a string and not a new promise. This is different from <code>.then()</code> which always returns a new promise.</p>
<p>With <code>await</code>, you can break up any chain of promises, and grab their resolve values. The following example uses the <code>fetch()</code> function—which is a promise—to show eliminating chaining with async/await.</p>
<pre><code class="lang-js"><span class="hljs-comment">// With chaining</span>
fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</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">result</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(result));

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// Array(10) [...]</span>

<span class="hljs-comment">// Without chaining</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchResource</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> response.json();
  <span class="hljs-built_in">console</span>.log(result);
}
fetchResource(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>);

<span class="hljs-comment">// Output on the console</span>

<span class="hljs-comment">// Array(10) [...]</span>
</code></pre>
<p>In the end, it boils down to preference and choice. If you prefer the chaining syntax, then go for it. If you prefer your code to look synchronous and want to use async/await, then that is fine too. </p>
<p>You can also use both syntaxes together, chaining promises inside an async function. It all depends on what you want to achieve and the style you prefer.</p>
<h2 id="heading-how-to-handle-errors-in-asyncawait">How to Handle Errors in Async/Await</h2>
<p>Just like with the normal promise syntax, you can catch errors properly using async/await. Properly handling errors in async calls is extremely important to track bugs. Use try/catch blocks to do this.</p>
<p><code>try</code> is a JavaScript keyword that wraps a block of code. As that block of code runs, <code>try</code> checks for errors. No error can escape a try block. Use <code>try</code> inside an <code>async</code> function.</p>
<p>The first error inside the <code>try</code> block stops the other instructions in that block from executing, <code>try</code> then passes the error value to the <code>catch</code> block. The <code>catch</code> block is similar to <code>.catch()</code> in promises. Just like the promise method, it is a function of an error.</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">fetchResource</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(result);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  }
}
</code></pre>
<p>In this example, the <code>catch</code> keyword has an error, which logs to the console. A settled promise with an uncaught error results in a rejected promise. Make sure you wrap your code in try/catch blocks to have more control over failures and faults in your program.</p>
<p>Also, just like the <code>.finally()</code> method for promises, you can use a <code>finally</code> block inside an async function. Braces that follow this keyword wrap around a block of code that would run regardless of if there is an error or not.</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">fetchResource</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(result);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Operation finished!"</span>);
  }
}
</code></pre>
<p>The use of the <code>finally</code> block is similar to the use of the <code>.finally()</code> method. This just proves that using an async function is a recent way to work with promises.</p>
<h2 id="heading-what-is-a-job-queue">What is a Job Queue?</h2>
<p>The Job Queue—also known as the Microtask Queue—is an important concept to be aware of in JavaScript. It was not originally a component of the JavaScript runtime, but the need for it came when promises became a part of JavaScript.</p>
<p>Consider the following code sample:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"This is a resolved value"</span>).then(<span class="hljs-built_in">console</span>.log);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-built_in">console</span>.log, <span class="hljs-number">0</span>, <span class="hljs-string">"This is a value after the timeout"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a normal log"</span>);
</code></pre>
<p>Here the first line is a promise that automatically resolves, then logs the value on the console. The second line is a timeout set to 0 milliseconds which means it is supposed to be instant. The timeout takes in a callback function that logs a value to the console. The third line is a normal console log.</p>
<p>When you run the program, can you guess the order in which these logs would appear? Let's find out.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Output on the console</span>
<span class="hljs-comment">/*
This is a normal log
This is a resolved value
--
undefined
--
This is a value after the timeout
*/</span>
</code></pre>
<p>This is an interesting output. The first log is from <code>console.log</code>. It is not so confusing because <code>console.log()</code> is not an async operation. The JavaScript engine will actively run every synchronous instruction immediately after the program starts.</p>
<p>The second line might be a little puzzling. It logs the resolved value of the promise. Why does the output from the promise come next? Well, the simple answer is that a promise is faster than any other async implementation in JavaScript. But that is not the full story.</p>
<p>In the JavaScript runtime, the event loop handles async operations. It can only call the callback functions of async instructions when the call stack is empty. Resolving a promise is an asynchronous operation, and it is understandable that it comes after a normal log. But why does it come before the <code>setTimeout()</code> instruction?</p>
<p>The JavaScript Runtime actually has these two queues—the Callback (or Macrotask) Queue and the Job (or Microtask) Queue. Shortly before the event loop starts calling the functions in the Callback Queue, it calls all the instructions on the Job Queue. The callback of a promise stays in the Job Queue so the event loop calls it first. This is why promises return values faster than any other async implementation.</p>
<p>The Job Queue is useful for some other instructions apart from promises. However, that is beyond the scope of this material. If you are curious, then you can <a target="_blank" href="https://blog.greenroots.info/task-queue-and-job-queue-deep-dive-into-javascript-event-loop-model">read more about the Job Queue here</a>.</p>
<p>A program returns immediately after taking care of the Job Queue. From the above code example, it returns with <code>undefined</code>. After that, the event loop moves over to the Callback Queue and executes the instructions there.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/event-loop.gif" alt="Illustration depicting the Microtask Queue and the Callback (Macrotask) Queue" width="600" height="400" loading="lazy">
<em>Image Credit: [Medium](https://medium.com/@saravanaeswari22/microtasks-and-macro-tasks-in-event-loop-7b408b2949e0"&gt;Saravanakumar on &lt;a href="https://medium.com)</em></p>
<p>The callback in <code>setTimeout()</code>will always move to the Callback Queue no matter how short the timer is. In the example, it logged last even though the timer was set to 0 milliseconds. </p>
<p>With that, I hope you understand why the example code produced that output, and the difference between the Callback Queue and the Microtask Queue.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This has been a deep dive into promises and async operations. In this article, you have learned how promises came about in JavaScript, what they are, and how to create them.  </p>
<p>You have also learned how to attach callbacks to a promise, how to catch errors in a promise, and how to run many promises simultaneously.</p>
<p>We also looked into the async/await syntax which is built on top of promises. You learned when they became a feature of JavaScript, how to create an async function, and how to use the await keyword. </p>
<p>You also learned how to handle errors using the syntax. Finally, the article explained what a Job Queue is.</p>
<p>Feel free to come back if you did not understand everything at once. JavaScript promises can take time to learn and master, but any JavaScript developer would benefit immensely from knowing how promises work. It gives you more control while writing professional async code for your applications. </p>
<p>Good luck building your next project.</p>
<p>PS: Follow me on <a target="_blank" href="https://twitter.com/EnyichiA">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/enyichiaagu/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Promises for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, a promise is a placeholder (proxy) for the value of an ongoing operation. You typically use a promise to manage situations where you must wait for the outcome of an operation. For example, uploading files to the server and awaiting the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-promises-for-beginners/</link>
                <guid isPermaLink="false">66d46162182810487e0ce1c0</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Spruce Emmanuel ]]>
                </dc:creator>
                <pubDate>Wed, 25 May 2022 14:56:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/05/Web-capture_11-5-2022_134720_127.0.0.1-1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, a promise is a placeholder (proxy) for the value of an ongoing operation.</p>
<p>You typically use a promise to manage situations where you must wait for the outcome of an operation. For example, uploading files to the server and awaiting the response of an API call, or just asking the user to choose a file from their computer.</p>
<p>You will learn about JavaScript promises in this article by building a real-world example app like the one below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/Web-capture_11-5-2022_134720_127.0.0.1.jpeg" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-is-a-promise">What is a Promise?</h2>
<p>A promise is simply a function that returns an <code>Object</code> which you can attach callbacks to.</p>
<p>The callbacks attached to a promise object will only get called when the operation completes. The callbacks will have to wait until the operation is <strong>fulfilled</strong> or <strong>rejected</strong>:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">`some_api_url`</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
  <span class="hljs-comment">// Everything here will wait the fetch operation to complete</span>
});
</code></pre>
<p>Before a promise finally settles (the promise either fulfills or gets rejected) it has to go through different states:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>State</td><td>Description</td><td>Callbcak</td></tr>
</thead>
<tbody>
<tr>
<td>pending</td><td>Means the operation is still running and the promise is pending</td><td>-</td></tr>
<tr>
<td>fulfilled</td><td>The operation was completed and it was successful</td><td><code>.then()</code></td></tr>
<tr>
<td>rejected</td><td>The operation was completed but there was an error</td><td><code>.catch()</code></td></tr>
<tr>
<td>settled</td><td>The promise has either resolved or rejected, either way this callback gets called</td><td><code>.finally()</code></td></tr>
</tbody>
</table>
</div><p>When a promise is created the initial state is pending. Then depending on the output of the operation the promise either gets fulfilled or rejected.</p>
<p>From the table above you can easily see the callback that will get called depending on each state of the Promise:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">`some_api_url`</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
  <span class="hljs-comment">// This will get called when the promise fulfills</span>
}).catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
  <span class="hljs-comment">// This will get called when the promise is rejected</span>
}).finally(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// This will get called all the time</span>
})
</code></pre>
<h2 id="heading-how-to-use-promises-in-javascript">How to Use Promises in JavaScript</h2>
<p>Now that you have learned what a promise it, let's demonstrate how you can use promises in JavaScript by building the movie search app we saw earlier.</p>
<p>A basic movie search app should have an input field where users can search for their favorite movies. It should also have a UI to display some basic info about the movie they searched for.</p>
<p>Let's get started by creating the <strong>HTML</strong>.</p>
<h3 id="heading-how-to-write-the-html">How to write the HTML</h3>
<p>For the sake of this tutorial and to display live examples, I am going to be using <strong>Codepen,</strong> but you can use your favorite code editor.</p>
<p>Create an <code>index.html</code> file and add the following code:</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"wrapper"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"header"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"header_logo"</span>&gt;</span>Movie<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"header_actions"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onsubmit</span>=<span class="hljs-string">"handle_form(event)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"header_form"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"header_form-icon"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"search"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"header_form-input"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Search, Press Enter to Submit"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"icon"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"22px"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"22px"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">use</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#icon-search"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"img_icon"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"32px"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"32px"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">""</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> &gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">main</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"main"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">article</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"movie"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"movie_img"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"img_src"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">""</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> <span class="hljs-attr">srcset</span>=<span class="hljs-string">""</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"movie_info"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"movie_title"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"movie_desc"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"movie_details"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Details<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex"</span>&gt;</span>
                  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Premiered: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"movie_date"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Rating: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"movie_rating"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Runtime: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"movie_runtime"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Status: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"movie_status"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
              <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">""</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener noreferrer"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"icon"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"16px"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"16px"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">use</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#icon-play"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
                Watch Movie<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"episodes_list"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"episodes_title"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">ol</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"episodes"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"episodes"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ol</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Above we just created the skeleton of our movie app. So now let's breath some life into it with some CSS:</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/Spruce_khalifa/embed/wvygzLq?editors=0100" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<h3 id="heading-how-to-fetch-a-movie">How to fetch a movie</h3>
<p>To fetch our movie, we are going to use the TVMAZE API. Create the <code>main.js</code> file and add the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> get_movie = <span class="hljs-function">(<span class="hljs-params">value = <span class="hljs-string">"Game of thrones"</span></span>) =&gt;</span> {
   fetch(
    <span class="hljs-string">`https://api.tvmaze.com/singlesearch/shows?q=<span class="hljs-subst">${value}</span>&amp;embed=episodes`</span>
  ).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> create_UI(response.json()));
};
</code></pre>
<p>We created a function <code>get_movie(value = "Game of thrones")</code> that uses the JavaScript fetch API. We use it to make a <code>GET</code> request to our movie API endpoint.</p>
<p>The fetch API returns a promise. To use the response from the API we attach the <code>.then()</code> callback in which we pass the <code>response.json()</code> into a new function <code>create_UI()</code>. Let's go ahead and create the <code>create_UI</code> function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> create_UI = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> movie_img = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#img_src"</span>);
  <span class="hljs-keyword">const</span> movie_icon = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#img_icon"</span>);
  <span class="hljs-keyword">const</span> movie_title = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".movie_title"</span>);
  <span class="hljs-keyword">const</span> movie_desc = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".movie_desc"</span>);
  <span class="hljs-keyword">const</span> movie_link = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".btn"</span>);
  <span class="hljs-keyword">const</span> movie_date = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#movie_date"</span>);
  <span class="hljs-keyword">const</span> movie_rating = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#movie_rating"</span>);
  <span class="hljs-keyword">const</span> movie_runtime = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#movie_runtime"</span>);
  <span class="hljs-keyword">const</span> movie_status = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#movie_status"</span>);

  <span class="hljs-comment">// set the UI</span>
  movie_icon.src = data.image.medium;
  movie_img.src = data.image.original;
  movie_title.textContent = data.name;
  movie_desc.innerHTML = data.summary;
  movie_link.href = data.officialSite;
  movie_date.textContent = data.premiered;
  movie_rating.textContent = data.rating.average;
  movie_runtime.textContent = data.runtime;
  movie_status.textContent = data.status;
};
</code></pre>
<p>The above function, as the name implies, helps us create the UI for our movie app. But of course we still need a way to collect the movie name from the users, so let's fix that.</p>
<p>The first thing we need to do is to add an <code>onsubmit</code> event handler to our HTML form:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onsubmit</span>=<span class="hljs-string">"search(event)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"header_form"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"search"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"header_form-input"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Search, Press Enter to Submit"</span> /&gt;</span>
//
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>Now in our <code>main.js</code> file we can handle what happens when we submit the form:</p>
<pre><code class="lang-js"><span class="hljs-comment">// handle form submit</span>
<span class="hljs-keyword">const</span> search = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  event.preventDefault();
  <span class="hljs-keyword">const</span> value = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".header_form-input"</span>).value;

  get_movie(value);
};
</code></pre>
<p>Anytime the user submits the form we get the value they entered in the search box and we pass it to the <code>get_movie(value = "Game of thrones")</code> function we created earlier.</p>
<h2 id="heading-promise-chaining">Promise Chaining</h2>
<p>Unlike what we have been seeing in our previous examples, the <code>.then()</code> callback is not really the end. That's because when you return value of a promise you get another promise. This becomes very useful when you want to run a series of asynchronous operations in order.</p>
<p>For example, our movie API doesn't just return info about a movie, it also returns information about all the episodes. Let's say that we really don't want to display all the episodes in Game of Thrones, we only want the first four (4) episodes.</p>
<p>With promise chaining we can easily achieve this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> get_movie = <span class="hljs-function">(<span class="hljs-params">value = <span class="hljs-string">"Game of thrones"</span></span>) =&gt;</span> {
  fetch(<span class="hljs-string">`https://api.tvmaze.com/singlesearch/shows?q=<span class="hljs-subst">${value}</span>&amp;embed=episodes`</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (data._embedded.episodes.length &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">const</span> new_data = data._embedded.episodes.slice(<span class="hljs-number">0</span>, <span class="hljs-number">4</span>);

        create_UI(data);
        <span class="hljs-keyword">return</span> create_episodesUI(new_data);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> create_UI(data);
      }
    });
};
</code></pre>
<p>This is still our <code>get_movie()</code> function, but this time instead of passing the data to the <code>create_UI</code> function we return the response <code>.then((response) =&gt; response.json())</code>. This creates a new promise, which we can attach more callbacks to.</p>
<p>Ideally this chain can keep going on and on for as long as you want. Remember all you have to do is to return the value of the promise.</p>
<h2 id="heading-how-to-handle-errors-in-promises">How to Handle Errors in Promises</h2>
<p>Errors that happen within a promise go immediately to the <code>.catch()</code> callback:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">`https://api.tvmaze.com/singlesearch/shows?q=<span class="hljs-subst">${value}</span>&amp;embed=episodes`</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-comment">// any error here will trigger the .catch() callback</span>
    }).catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-comment">// all errors are caught and handled here</span>
    })
</code></pre>
<p>The <code>.catch()</code> callback is short for <code>.then(null, (error) =&gt; {})</code>. You could also write the above as:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">`https://api.tvmaze.com/singlesearch/shows?q=<span class="hljs-subst">${value}</span>&amp;embed=episodes`</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-comment">// any error here will trigger the .catch() callback</span>
    }, <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-comment">// all errors are caught and handled here</span>
    })
</code></pre>
<p>With our movie search app, for example, when we encounter any errors we can handle and display a nice error message to users in the <code>.catch()</code> callback:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> get_movie = <span class="hljs-function">(<span class="hljs-params">value = <span class="hljs-string">"Game of thrones"</span></span>) =&gt;</span> {
  fetch(<span class="hljs-string">`https://api.tvmaze.com/singlesearch/shows?q=<span class="hljs-subst">${value}</span>&amp;embed=episodes`</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (data._embedded.episodes.length &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">const</span> new_data = data._embedded.episodes.slice(<span class="hljs-number">0</span>, <span class="hljs-number">4</span>);

        create_UI(data);
        <span class="hljs-keyword">return</span> create_episodesUI(new_data);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> create_UI(data);
      }
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(error.message);
      <span class="hljs-comment">// Challange: display your error here</span>
    });
};
</code></pre>
<p>Now if for any reason we get an error, the <code>.catch()</code> callback is called and we display the correct error to the user.</p>
<h2 id="heading-how-to-create-promises-in-javascript">How to Create Promises in JavaScript</h2>
<p>Now that we have learned what promises are and how to use them, let's see how we can create a promise in JavaScript.</p>
<p>To create a promise in JavaScript, you use the promise constructor. The constructor takes one argument: a function with two parameters, <code>resolve</code> and <code>reject</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> is_true = <span class="hljs-literal">true</span>
<span class="hljs-keyword">const</span> new_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-keyword">if</span>(is_true) {
    <span class="hljs-comment">// everything went fine</span>
    resolve()
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// Oops there was an error</span>
    reject()
  }
})
</code></pre>
<p>Then we can go ahead and use our <code>new_promise</code> by attaching the callbacks:</p>
<pre><code class="lang-js">new_promise
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-comment">// everything went fine</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-comment">// handle errors</span>
  });
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we learnt about promises, what they are, and how to use them by building a movie search app. The entire code and live preview of our movie app can be found on Codepen: <a target="_blank" href="https://codepen.io/Spruce_khalifa/pen/wvygzLq?editors=0100">Movie Search App</a>.</p>
<h3 id="heading-challenge">Challenge</h3>
<p>While creating our movie app, I left out some parts which I think would be great for you to practice your new Promise skills:</p>
<ol>
<li><p>Our movie app looks frozen when we are waiting for the API response. You can try adding a loader to tell the user that the promise is pending.</p>
</li>
<li><p>We currently just use <code>console.log(error)</code> to log out errors. But we don't want that, so you can figure out how to display all errors to users in a friendly way.</p>
</li>
</ol>
<p>If you created something wonderful with this, please feel free to tweet about it and tag me <a target="_blank" href="https://twitter.com/sprucekhalifa">@sprucekhalifa</a>. And don't forget to hit the follow button.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Promises – The promise.then, promise.catch and promise.finally Methods Explained ]]>
                </title>
                <description>
                    <![CDATA[ By Dillion Megida A promise is an object in JavaScript that will produce a value sometime in the future. This usually applies to asynchronous operations. In applications, asynchronous operations happen a lot. This can be API requests, delayed data pr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-promise-methods/</link>
                <guid isPermaLink="false">66d84f32c15439a8d5631e60</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 16 May 2022 18:30:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/05/pexels-pixabay-532414.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dillion Megida</p>
<p>A promise is an object in JavaScript that will produce a value sometime in the future. This usually applies to asynchronous operations.</p>
<p>In applications, asynchronous operations happen a lot. This can be API requests, delayed data processing, and much more. </p>
<p>Instead of having to block code execution until the data loads, you can define them as promises, so that code execution continues with other parts of the code. And when the promises complete, you can use the data in them.</p>
<p>You can learn more about <a target="_blank" href="https://dillionmegida.com/p/javascript-promises/">promises in this simplified article</a>.</p>
<p>In some cases a promise passes, and in other cases it fails. How do you handle the result from each outcome?</p>
<p>For the rest of this article, we will understand the <code>then</code>, <code>catch</code> and <code>finally</code> methods of promises.</p>
<h2 id="heading-the-states-of-promises-in-javascript">The states of promises in JavaScript</h2>
<p>A promise has three states:</p>
<ul>
<li><strong>pending</strong>: the promise is still in the works</li>
<li><strong>fulfilled</strong>: the promise resolves successfully and returns a value</li>
<li><strong>rejected</strong>: the promise fails with an error</li>
</ul>
<p>The <strong>fulfilled</strong> and <strong>rejected</strong> states have one thing in common: whether a promise is fulfilled or rejected, the promise is <strong>settled</strong>. So a settled state could either be a fulfilled or a rejected promise.</p>
<h2 id="heading-when-a-promise-is-fulfilled">When a promise is fulfilled</h2>
<p>When a promise is fulfilled, you can access the resolved data in the <code>then</code> method of the promise:</p>
<pre><code class="lang-js">promise.then(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
 <span class="hljs-comment">// use value for something</span>
})
</code></pre>
<p>Think of the <code>then</code> method as "this works and <strong>then</strong> do this with the data returned from the promise". If there is no data, you can skip the <code>then</code> method.</p>
<p>It's also possible that the <code>then</code> method can return another promise, so you can chain another <code>then</code> method like this:</p>
<pre><code class="lang-js">promise
  .then(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> value.anotherPromise()
  })
  .then(<span class="hljs-function"><span class="hljs-params">anotherValue</span> =&gt;</span> {
    <span class="hljs-comment">// use this value</span>
  })
</code></pre>
<h2 id="heading-when-a-promise-is-rejected">When a promise is rejected</h2>
<p>When a promise is rejected (that is, the promise fails), you can access the error information returned in the <code>catch</code> method of the promise:</p>
<pre><code class="lang-js">promise.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
  <span class="hljs-comment">// interpret error and maybe display something on the UI</span>
})
</code></pre>
<p>Promises can fail for different reasons. For API requests, it can be a failed network connection, or a returned error from the server. Such promises will be rejected if they get errors.</p>
<p>Think of the <code>catch</code> method as "this does not work so I <strong>catch</strong> the error so that it does not break the application". If you do not catch the error, this can break your application in some cases.</p>
<h2 id="heading-when-a-promise-settles">When a promise settles</h2>
<p>There's a last stage of the promise. Whether the promise is fulfilled or is rejected, the promise has been completed (has been <strong>settled</strong>). At this completed stage, you can <code>finally</code> do something.</p>
<p>The <code>finally</code> method of promises is useful when you want to do something after the promise has settled. This can be cleanup or code you may want to duplicate in the <code>then</code> and <code>catch</code> methods.</p>
<p>For example, instead of doing:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dataIsLoading = <span class="hljs-literal">true</span>;

promise
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-comment">// do something with data</span>
    dataIsLoading = <span class="hljs-literal">false</span>;
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
   <span class="hljs-comment">// do something with error</span>
   dataIsLoading = <span class="hljs-literal">false</span>;
  })
</code></pre>
<p>You can use the <code>finally</code> method like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dataIsLoading = <span class="hljs-literal">true</span>;

promise
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-comment">// do something with data</span>
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
   <span class="hljs-comment">// do something with error</span>
  })
  .finally(<span class="hljs-function">() =&gt;</span> {
    dataIsLoading = <span class="hljs-literal">false</span>;
  })
</code></pre>
<p>The <code>finally</code> method is called regardless of the outcome (fulfilled or rejected) of the promise.</p>
<h2 id="heading-wrap-up">Wrap up</h2>
<p>Promises have the <code>then</code>, <code>catch</code> and <code>finally</code> methods for doing different things depending on the outcome of a promise. In summary:</p>
<ul>
<li><code>then</code>: when a promise is successful, you can <strong>then</strong> use the resolved data</li>
<li><code>catch</code>: when a promise fails, you <strong>catch</strong> the error, and do something with the error information</li>
<li><code>finally</code>: when a promise settles (fails or passes), you can <strong>finally</strong> do something</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Synchronous vs Asynchronous JavaScript – Call Stack, Promises, and More ]]>
                </title>
                <description>
                    <![CDATA[ Let me start this article by asking, "What is JavaScript"? Well, here's the most confusing yet to-the-point answer I have found so far: JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript/</link>
                <guid isPermaLink="false">66be001e422f318982ba47cd</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tapas Adhikary ]]>
                </dc:creator>
                <pubDate>Mon, 13 Sep 2021 21:00:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/freeCodeCamp-Cover-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Let me start this article by asking, "What is JavaScript"? Well, here's the most confusing yet to-the-point answer I have found so far:</p>
<blockquote>
<p>JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibility.</p>
</blockquote>
<p>Hold on a second – did it say single-threaded and asynchronous at the same time? If you understand what single-threaded means, you'll likely mostly associate it with synchronous operations. How can JavaScript be asynchronous, then?</p>
<p>In this article, we will learn all about the synchronous and asynchronous parts of JavaScript. You use both in web programming almost daily. </p>
<p>If you like to learn from video content as well, this article is also available as a video tutorial here: 🙂</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/pIjfzjsoVw4" 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-in-this-article-youll-learn">In this article, You'll Learn:</h1>
<ul>
<li>How JavaScript is synchronous.</li>
<li>How asynchronous operations occur when JavaScript is single-threaded.</li>
<li>How understanding synchronous vs. asynchronous helps you better understand JavaScript promises.</li>
<li>Lots of simple but powerful examples to cover these concepts in detail.</li>
</ul>
<h1 id="heading-javascript-functions-are-first-class-citizens">JavaScript Functions are First-Class Citizens</h1>
<p>In JavaScript, you can create and modify a function, use it as an argument, return it from another function, and assign it to a variable. All these abilities allow us to use functions everywhere to place a bunch of code logically.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/block-function.png" alt="Image" width="600" height="400" loading="lazy">
<em>Lines of code organized into functions logically</em></p>
<p>We need to tell the JavaScript engine to execute functions by invoking them. It'll look like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Do something</span>
    <span class="hljs-comment">// Do something again</span>
    <span class="hljs-comment">// Again</span>
    <span class="hljs-comment">// So on...</span>
}

<span class="hljs-comment">// Invoke the function</span>
f1();
</code></pre>
<p>By default, every line in a function executes sequentially, one line at a time. The same is applicable even when you invoke multiple functions in your code. Again, line by line.</p>
<h1 id="heading-synchronous-javascript-how-the-function-execution-stack-works">Synchronous JavaScript – How the Function Execution Stack Works</h1>
<p>So what happens when you define a function and then invoke it? The JavaScript engine maintains a <code>stack</code> data structure called <code>function execution stack</code>. The purpose of the stack is to track the current function in execution. It does the following:</p>
<ul>
<li>When the JavaScript engine invokes a function, it adds it to the stack, and the execution starts.</li>
<li>If the currently executed function calls another function, the engine adds the second function to the stack and starts executing it.</li>
<li>Once it finishes executing the second function, the engine takes it out from the stack.</li>
<li>The control goes back to resume the execution of the first function from the point it left it last time.</li>
<li>Once the execution of the first function is over, the engine takes it out of the stack.</li>
<li>Continue the same way until there is nothing to put into the stack.</li>
</ul>
<p>The function execution stack is also known as the <code>Call Stack</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/stack.png" alt="Image" width="600" height="400" loading="lazy">
<em>Function Execution Stack</em></p>
<p>Let's look at an example of three functions that execute one by one:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f1</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// some code</span>
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f2</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// some code</span>
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f3</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// some code</span>
}

<span class="hljs-comment">// Invoke the functions one by one</span>
f1();
f2();
f3();
</code></pre>
<p>Now let's see what happens with the function execution stack:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/first-flow.gif" alt="Image" width="600" height="400" loading="lazy">
<em>A step-by-step flow shows the execution order</em></p>
<p>Did you see what happened there? First, <code>f1()</code> goes into the stack, executes, and pops out. Then <code>f2()</code> does the same, and finally <code>f3()</code>. After that, the stack is empty, with nothing else to execute.</p>
<p>Ok, let's now work through a more complex example. Here is a function <code>f3()</code> that invokes another function <code>f2()</code> that in turn invokes another function <code>f1()</code>.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f1</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Some code</span>
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f2</span>(<span class="hljs-params"></span>) </span>{
  f1();
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f3</span>(<span class="hljs-params"></span>) </span>{
  f2();
}
f3();
</code></pre>
<p>Let's see what's going on with the function execution stack:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/second-flow.gif" alt="Image" width="600" height="400" loading="lazy">
<em>A step-by-step flow shows the execution order</em></p>
<p>Notice that first <code>f3()</code> gets into the stack, invoking another function, <code>f2()</code>. So now <code>f2()</code> gets inside while <code>f3()</code> remains in the stack. The <code>f2()</code> function invokes <code>f1()</code>. So, time for <code>f1()</code> to go inside the stack with both <code>f2()</code> and <code>f3()</code> remaining inside.</p>
<p>First, <code>f1()</code> finishes executing and comes out of the stack. Right after that <code>f2()</code> finishes, and finally <code>f3()</code>.</p>
<p>The bottom line is that everything that happens inside the <code>function execution stack</code> is sequential. This is the <code>Synchronous</code> part of JavaScript. JavaScript's <code>main</code> thread makes sure that it takes care of everything in the stack before it starts looking into anything <code>elsewhere</code>.</p>
<p>Great! Now that we understand how <code>synchronous</code> operations work in JavaScript, let's now flip the coin and see its <code>asynchronous</code> side. Are you ready?</p>
<h1 id="heading-asynchronous-javascript-how-browser-apis-and-promises-work">Asynchronous JavaScript – How Browser APIs and Promises Work</h1>
<p>The word <code>asynchronous</code> means <strong>not occurring at the same time</strong>. What does it mean in the context of JavaScript? </p>
<p>Typically, executing things in sequence works well. But you may sometimes need to fetch data from the server or execute a function with a delay, something you do not anticipate occurring <code>NOW</code>. So, you want the code to execute <code>asynchronously</code>.</p>
<p>In these circumstances, you may not want the JavaScript engine to halt the execution of the other sequential code. So, the JavaScript engine needs to manage things a bit more efficiently in this case.</p>
<p>We can classify most asynchronous JavaScript operations with two primary triggers:</p>
<ol>
<li><strong>Browser API/Web API</strong> events or functions. These include methods like <code>setTimeout</code>, or event handlers like click, mouse over, scroll, and many more.</li>
<li><strong>Promises</strong>. A unique JavaScript object that allows us to perform asynchronous operations.</li>
</ol>
<p>Don't worry if you are new to promises. You do not need to know more than this to follow this article. At the end of the article, I have provided some links so you can start learning promises in the most beginner-friendly way.</p>
<h2 id="heading-how-to-handle-browser-apisweb-apis">How to Handle Browser APIs/Web APIs</h2>
<p>Browser APIs like <code>setTimeout</code> and event handlers rely on <code>callback</code> functions. A callback function executes when an asynchronous operation completes. Here is an example of how a <code>setTimeout</code> function works:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printMe</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'print me'</span>);
}

<span class="hljs-built_in">setTimeout</span>(printMe, <span class="hljs-number">2000</span>);
</code></pre>
<p>The <code>setTimeout</code> function executes a function after a certain amount of time has elapsed. In the code above, the text <code>print me</code> logs into the console after a delay of 2 seconds.</p>
<p>Now assume we have a few more lines of code right after the <code>setTimeout</code> function like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printMe</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'print me'</span>);
}

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

<span class="hljs-built_in">setTimeout</span>(printMe, <span class="hljs-number">2000</span>);
test();
</code></pre>
<p>So, what do we expect to happen here? What do you think the output will be?</p>
<p>Will the JavaScript engine wait for 2 seconds to go to the invocation of the <code>test()</code> function and output this:</p>
<pre><code class="lang-shell">printMe
test
</code></pre>
<p>Or will it manage to keep the callback function of <code>setTimeout</code> aside and continue its other executions? So the output could be this, perhaps:</p>
<pre><code class="lang-shell">test
printMe
</code></pre>
<p> If you guessed the latter, you're right. That's where the asynchronous mechanism kicks in.</p>
<h2 id="heading-how-the-javascript-callback-queue-works-aka-task-queue">How the JavaScript Callback Queue Works (aka Task Queue)</h2>
<p>JavaScript maintains a queue of callback functions. It is called a callback queue or task queue. A queue data structure is <code>First-In-First-Out(FIFO)</code>. So, the callback function that first gets into the queue has the opportunity to go out first. But the question is:</p>
<ul>
<li>When does the JavaScript engine put it in the queue?</li>
<li>When does the JavaScript engine take it out of the queue?</li>
<li>Where does it go when it comes out of the queue?</li>
<li>Most importantly, how do all these things relate to the asynchronous part of JavaScript?</li>
</ul>
<p>Whoa, lots of questions! Let's figure out the answers with the help of the following image:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/taskQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The above image shows the regular <code>call stack</code> we have seen already. There are two additional sections to track if a browser API (like setTimeout) kicks in and <code>queue</code>s the callback function from that API.</p>
<p>The JavaScript engine keeps executing the functions in the call stack. As it doesn't put the callback function straight into the stack, there is no question of any code waiting for/blocking execution in the stack.</p>
<p>The engine creates a <code>loop</code> to look into the queue periodically to find what it needs to pull from there. It pulls a callback function from the queue to the call stack when the stack is empty. Now the callback function executes generally as any other function in the stack. The loop continues. This loop is famously known as the <code>Event Loop</code>.</p>
<p>So, the moral of the story is:</p>
<ul>
<li>When a Browser API occurs, park the callback functions in a queue.</li>
<li>Keep executing code as usual in the stack.</li>
<li>The event loop checks if there is a callback function in the queue.</li>
<li>If so, pull the callback function from the queue to the stack and execute.</li>
<li>Continue the loop.</li>
</ul>
<p>Alright, let's see how it works with the code below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'f1'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f2</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'f2'</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-built_in">console</span>.log(<span class="hljs-string">'main'</span>);

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

    f2();
}

main();
</code></pre>
<p>The code executes a <code>setTimeout</code> function with a callback function <code>f1()</code>. Note that we have given zero delays to it. This means that we expect the function <code>f1()</code> to execute immediately. Right after setTimeout, we execute another function, <code>f2()</code>.</p>
<p>So, what do you think the output will be? Here it is:</p>
<pre><code class="lang-shell">main
f2
f1
</code></pre>
<p>But, you may think that <code>f1</code> should print before <code>f2</code> as we do not delay f1 to execute. But no, that's not the case. Remember the <code>event loop</code> mechanism we discussed above? Now, let's see it in a step-by-step flow for the above code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/third-flow.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Event loop - see the step-by-step execution</em></p>
<p>Here are steps written out:</p>
<ol>
<li>The <code>main()</code> function gets inside the call stack.</li>
<li>It has a console log to print the word main. The <code>console.log('main')</code> executes and goes out of the stack.</li>
<li>The setTimeout browser API takes place.</li>
<li>The callback function puts it into the callback queue.</li>
<li>In the stack, execution occurs as usual, so <code>f2()</code> gets into the stack. The console log of <code>f2()</code> executes. Both go out of the stack.</li>
<li>The <code>main()</code> also pops out of the stack.</li>
<li>The event loop recognizes that the call stack is empty, and there is a callback function in the queue.</li>
<li>The callback function <code>f1()</code> then goes into the stack. Execution starts. The console log executes, and <code>f1()</code> also comes out of the stack.</li>
<li>At this point, nothing else is in the stack and queue to execute further.</li>
</ol>
<p>I hope it's now clear to you how the <code>asynchronous</code> part of JavaScript works internally. But, that's not all. We have to look at <code>promises</code>.</p>
<h2 id="heading-how-the-javascript-engine-handles-promises">How the JavaScript Engine Handles Promises</h2>
<p>In JavaScript, promises are special objects that help you perform asynchronous operations. </p>
<p>You can create a promise using the <code>Promise</code> constructor. You need to pass an <code>executor</code> function to it. In the executor function, you define what you want to do when a promise returns successfully or when it throws an error. You can do that by calling the <code>resolve</code> and <code>reject</code> methods, respectively.</p>
<p>Here is an example of a promise in JavaScript:</p>
<pre><code class="lang-js"><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>
        resolve(<span class="hljs-string">'I am a resolved promise'</span>);
);
</code></pre>
<p>After the promise is executed, we can handle the result using the <code>.then()</code> method and any errors with the <code>.catch()</code> method.</p>
<pre><code class="lang-js">promise.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(result))
</code></pre>
<p>You use promises every time you use the <code>fetch()</code> method to get some data from a store. </p>
<p>The point here is that JavaScript engine doesn't use the same <code>callback queue</code> we have seen earlier for browser APIs. It uses another special queue called the <code>Job Queue</code>.</p>
<h2 id="heading-what-is-the-job-queue-in-javascript">What is the Job Queue in JavaScript?</h2>
<p>Every time a promise occurs in the code, the executor function gets into the job queue. The event loop works, as usual, to look into the queues but gives priority to the <code>job queue</code> items over the <code>callback queue</code> items when the <code>stack</code> is free. </p>
<p>The item in the callback queue is called a <code>macro task</code>, whereas the item in the job queue is called a <code>micro task</code>.</p>
<p>So the entire flow goes like this:</p>
<ul>
<li>For each loop of the <code>event loop</code>, one task is completed out of the <code>callback queue</code>.</li>
<li>Once that task is complete, the event loop visits the <code>job queue</code>. It completes all the <code>micro tasks</code> in the job queue before it looks into the next thing.</li>
<li>If both the queues got entries at the same point in time, the <code>job queue</code> gets preference over the <code>callback queue</code>.</li>
</ul>
<p>The image below shows the inclusion of the job queue along with other preexisting items.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/JObQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now, let's look at an example to understand this sequence better:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'f1'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f2</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'f2'</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-built_in">console</span>.log(<span class="hljs-string">'main'</span>);

    <span class="hljs-built_in">setTimeout</span>(f1, <span class="hljs-number">0</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>
        resolve(<span class="hljs-string">'I am a promise'</span>)
    ).then(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(resolve))

    f2();
}

main();
</code></pre>
<p>In the above code, we have a <code>setTimeout()</code> function as before, but we have introduced a promise right after it. Now remember all that we have learned and guess the output.</p>
<p>If your answer matches this, you are correct:</p>
<pre><code class="lang-shell">main
f2
I am a promise
f1
</code></pre>
<p>Now let's see the flow of actions:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/fourth-flow.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Callback queue vs. Job queue</em></p>
<p>The flow is almost the same as above, but it is crucial to notice how the items from the job queue prioritize the items from the task queue. Also note that it doesn't even matter if the <code>setTimeout</code> has zero delay. It is always about the job queue that comes before the callback queue.</p>
<p>Alright, we have learned everything we need to understand synchronous and asynchronous execution in JavaScript.</p>
<h1 id="heading-here-is-a-quiz-for-you">Here is a Quiz for You!</h1>
<p>Let's test your understanding by taking a quiz. Guess the output of the following code and apply all the knowledge we have gained so far:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f1</span>(<span class="hljs-params"></span>) </span>{
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'f1'</span>);
}

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

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f3</span>(<span class="hljs-params"></span>) </span>{ 
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'f3'</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-built_in">console</span>.log(<span class="hljs-string">'main'</span>);

  <span class="hljs-built_in">setTimeout</span>(f1, <span class="hljs-number">50</span>);
  <span class="hljs-built_in">setTimeout</span>(f3, <span class="hljs-number">30</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>
    resolve(<span class="hljs-string">'I am a Promise, right after f1 and f3! Really?'</span>)
  ).then(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(resolve));

  <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>
    resolve(<span class="hljs-string">'I am a Promise after Promise!'</span>)
  ).then(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(resolve));

  f2();
}

main();
</code></pre>
<p>Here is the expected output:</p>
<pre><code class="lang-shell">main
f2
I am a Promise, right after f1 and f3! Really?
I am a Promise after Promise!
f3
f1
</code></pre>
<p>Do you want more such quizzes? <a target="_blank" href="https://github.com/atapas/promise-interview-ready">Head over to this repository</a> to practice more exercises.</p>
<p>In case you are stuck or need any clarifications, my DM is always <a target="_blank" href="https://twitter.com/tapasadhikary">open on Twitter</a>.</p>
<h1 id="heading-in-summary">In Summary</h1>
<p>To summarize:</p>
<ul>
<li>The JavaScript engine uses the stack data structure to keep track of currently executed functions. The stack is called the function execution stack.</li>
<li>The function execution stack (aka call stack) executes the functions sequentially, line-by-line, one-by-one.</li>
<li>The browser/web APIs use callback functions to complete the tasks when an asynchronous operation/delay is done. The callback function is placed in the callback queue.</li>
<li>The promise executor functions are placed in the job queue.</li>
<li>For each loop of the event loop, one macro task is completed out of the callback queue.</li>
<li>Once that task is complete, the event loop visits the job queue. It completes all the micro-tasks in the job queue before it looks for the next thing.</li>
<li>If both the queues get entries at the same point in time, the job queue gets preference over the callback queue.</li>
</ul>
<h1 id="heading-before-we-end">Before We End...</h1>
<p>That's all for now. I hope you've found this article insightful, and that it helps you understand JavaScript's synchronous vs asynchronous concepts better.</p>
<p>Let's connect. You can follow me on <a target="_blank" href="https://twitter.com/tapasadhikary">Twitter(@tapasadhikary)</a>, My <a target="_blank" href="https://youtube.com/c/TapasAdhikary?sub_confirmation=1">Youtube channel</a>, and <a target="_blank" href="https://github.com/atapas">GitHub(atapas)</a>.</p>
<p>As promised before, here are a few articles you may find useful,</p>
<ul>
<li><a target="_blank" href="https://blog.greenroots.info/javascript-promises-explain-like-i-am-five">JavaScript Promises - Explain Like I'm Five</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/javascript-promise-chain-the-art-of-handling-promises">JavaScript Promise Chain - The art of handling promises</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/javascript-async-and-await-in-plain-english-please">JavaScript async and await - in plain English, please</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/introducing-promiviz-visualize-and-learn-javascript-promise-apis">Introducing PromiViz - visualize and learn JavaScript promise APIs</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Promise? JavaScript Promises for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ If you're a JavaScript beginner, you might be struggling to understand what a promise really is. I recently published this as a thread on Twitter and was blown away by the responses. So I decided to expand this into an introductory tutorial on JavaSc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-promise-in-javascript-for-beginners/</link>
                <guid isPermaLink="false">66d4619c7df3a1f32ee7f8c0</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kingsley Ubah ]]>
                </dc:creator>
                <pubDate>Mon, 16 Aug 2021 22:56:20 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/JS-Promises-Expl.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're a JavaScript beginner, you might be struggling to understand what a promise really is.</p>
<p>I recently published this as a thread on Twitter and was blown away by the responses. So I decided to expand this into an introductory tutorial on JavaScript promises.</p>
<p>I have read a lot of articles on promises and the problem is that many of these guides don't explain them in a relatable way. People don't understand what a promise is in JavaScript is because they don't really know what it is about and how it behaves in simple and relatable terms.</p>
<p>So in this article, I will be telling you a short story which explains what promises are and how exactly they work. I will also show you how to use promises in your JavaScript with some examples.</p>
<h2 id="heading-what-is-a-promise-in-javascript">What is a Promise in JavaScript?</h2>
<p>Imagine that you are interviewing job seekers for a position at your company.</p>
<p>A young man frantically comes in for an interview. When his interview session is about to begin, he realizes that he has forgotten his résumé.</p>
<p>Bummer, right?</p>
<p>He's not daunted, though. Luckily for him, he has a roommate who was still at home at that time.</p>
<p>He quickly calls his roommate over the phone and asks him for help. He pleads with his roommate to help find his résumé. His roommate PROMISES to text back as soon as he has something to report.</p>
<p>Assuming the résumé is eventually found, he can text back:</p>
<blockquote>
<p>“Successful, I found your resume!”</p>
</blockquote>
<p>But if he doesn't find it, he is supposed to text back a failure message with the reason why he couldn't find the résumé. For example, he may text this message over to his friend who's interviewing:</p>
<blockquote>
<p>“Sorry, I couldn’t find your résumé because the key to your safe is missing.”</p>
</blockquote>
<p>In the meantime, the interview continues as planned, and the interviewer holds on to the promise of finding the résumé, and not the actual résumé. At that time, the interviewer sets the status of the résumé delivery to PENDING.</p>
<p>The interviewee answers all the questions he is asked. But ultimately, his employment still depends on the FINAL STATUS of his résumé.</p>
<p>His roommate finally texts back. As we discussed before, if he didn't find the résumé, he will share this failure with you along with the reason why he didn't find it.</p>
<p>When that happens, the interview will end and the interviewee will be rejected.</p>
<p>On the other hand, if the roommate finds the résumé, he will happily tell his friend that he was successful, and he will go ahead and FULFILL his hopes of getting a job.</p>
<h2 id="heading-so-how-does-this-translate-to-js-code">So How Does This Translate to JS Code?</h2>
<p>The roommate promising to find the résumé and texting back is synonymous with how we define a promise in JavaScript. The code does not directly or immediately return a value. Instead, it returns a promise that it will eventually provide the value at a later time.</p>
<p>A promise in JavaScript is asynchronous, meaning it takes time to resolve or finish. Just as the search for the applicant's resume takes time to complete.</p>
<p>For that reason, the interviewer decides not to sit around doing nothing, so they begin interviewing the candidate based on the promise of a résumé delivery. We're using the promise of returning a résumé in place of an actual resume.</p>
<p>The JS engine also doesn’t wait around doing nothing – it starts executing other parts of the code, pending the returned value of the promise.</p>
<p>The message text contains the status message of the résumé search. With a JavaScript Promise, that is also called the return value.</p>
<p>If the message is a “success”, we will proceed to sign the candidate in and grant him the position. If it fails, we proceed to reject his application.</p>
<p>With JavaScript promises, we do this by <a target="_blank" href="https://www.freecodecamp.org/news/javascript-callback-functions-what-are-callbacks-in-js-and-how-to-use-them/">using a callback function</a> (promise handlers). These functions are defined in a nested <code>then()</code> method.</p>
<p>To specify what callbacks to call, you use the following two functions:</p>
<ul>
<li><p><code>resolve(value)</code>: This indicates that the asynchronous task was successful. This will call the fulfillment callback in the <code>then()</code> handler.</p>
</li>
<li><p><code>reject(error)</code>: This indicates an error while trying to run the asynchronous task. This will call the rejection callback in the <code>then()</code> handler.</p>
</li>
</ul>
<p>If the promise is successful, the fulfillment callback will be called. If the promise is rejected, the rejected call back will be called instead.</p>
<p>A promise is simply a placeholder for an asynchronous task which is yet to be completed. When you define a promise object in your script, instead of returning a value immediately, it returns a promise.</p>
<h2 id="heading-how-to-write-a-promise-in-javascript">How to Write a Promise in JavaScript</h2>
<p>You can define a promise in your JavaScript by calling the <code>Promise</code> class and constructing an object like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'this is the eventual value the promise will return'</span>);
  }, <span class="hljs-number">300</span>);
});

<span class="hljs-built_in">console</span>.log(myPromise);
</code></pre>
<p>Running this in the console will return a <code>Promise</code> object:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/promise-console-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Constructing an object is not the only way you can define a promise, though. You can also use the built-in <code>Promise</code> API to achieve the same thing:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> anotherPromise = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"this is the eventual value the promise will return"</span>)

<span class="hljs-built_in">console</span>.log(anotherPromise);
</code></pre>
<p>While the promise in the first code sample will wait for 3 seconds before fulfilling the promise with the <code>this is the eventual...</code> message, the promise in the second code sample will immediately fulfill it with the same message.</p>
<h2 id="heading-rejected-promises-in-javascript">Rejected Promises in JavaScript</h2>
<p>A Promise can also be rejected. Most of the time, rejections occur because JS encountered some kind of error while running the Asynchronous code. In such a scenario, it calls the <code>reject()</code> function instead.</p>
<p>Here is simple and contrived example of how a promise can get rejected:</p>
<pre><code class="lang-js"><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-keyword">let</span> a = <span class="hljs-literal">false</span>;
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> (a) ? resolve(<span class="hljs-string">'a is found!'</span>): reject(<span class="hljs-string">'sorry, no a'</span>);
  }, <span class="hljs-number">300</span>);
});
</code></pre>
<p>Can you think of the reason why this promise gets rejected? If you said "because <code>a</code> is not false", congratulations!</p>
<p>The promise in the third code sample will resolve to a rejection after a timeout of three seconds, because the <code>(a)?</code> statement resolves to false, which will trigger <code>reject</code>.</p>
<h2 id="heading-how-to-chain-promises-with-then">How to Chain Promises with <code>then()</code></h2>
<p>When the promise finally returns a value, you will typically want to do something with that return value.</p>
<p>For example, if you were making a network request, you might want to access the value and display it on the page for the user.</p>
<p>You can define two callback functions which you want to get called when a promise is either fulfilled or rejected. These functions are defined inside a nested <code>then()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> anotherPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'this is the eventual value the promise will return'</span>);
  }, <span class="hljs-number">300</span>);
});

<span class="hljs-comment">// CONTINUATION</span>
anotherPromise
.then(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> { <span class="hljs-built_in">console</span>.log(value) })
</code></pre>
<p>Running this code will display the fulfillment message after three seconds in the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/EVENTAL-RETURN.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Note that you can nest as many promises as you want. Each step will execute after the previous step, taking in the return value of that previous step:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> anotherPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'this is the eventual value the promise will return'</span>);
  }, <span class="hljs-number">300</span>);
});

anotherPromise
.then(fulfillFn, rejectFn)
.then(fulfilFn, rejectFn)
.then(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> { <span class="hljs-built_in">console</span>.log(value) })
</code></pre>
<p>But we have missed something important.</p>
<p>Always keep in mind that a <code>then()</code> method must take both the fulfillment hander and a rejection handler. This way, the first is called if the promise is fulfilled and the second is called if the promise is rejected with an error.</p>
<p>The promises in code samples four and five does not include a second handler. So, assuming that an error is encountered, there would be no rejection handler to handle the error.</p>
<p>If you are only going to define a single callback function (aka a fulfillment handler) in <code>then()</code>, then you will need to nest a <code>catch()</code> method at the bottom of the promise chain to catch any possible errors.</p>
<h3 id="heading-how-to-use-the-catch-method-in-js">How to Use the <code>catch()</code> Method in JS</h3>
<p>The <code>catch()</code> method will always get called whenever an error is encountered at any point along the promise chain:</p>
<pre><code class="lang-js"><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-keyword">let</span> a = <span class="hljs-literal">false</span>;
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> (a) ? resolve(<span class="hljs-string">'a is found!'</span>): reject(<span class="hljs-string">'sorry, no a'</span>);
  }, <span class="hljs-number">300</span>);
}); 

myPromise
.then(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> { <span class="hljs-built_in">console</span>.log(value) })
.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>Since <code>myPromise</code> will eventually resolve to a rejection, the function defined in the nested <code>then()</code> will be ignored. Instead, the error handler in <code>catch()</code> will run, which should log the following error message to the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Catch.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>JavaScript promises are a very powerful feature that help you run asynchronous code in JavaScript. In most, if not all, interviews for roles which use JavaScript, your interviewer will probably ask a question about promises.</p>
<p>In this article, I have explained what a promise is in simple terms, and I've shown its basic practical usage with some code examples.</p>
<p>I hope you got something useful from this article. If you like programming-related tutorials like this, you should <a target="_blank" href="https://ubahthebuilder.tech/user-authentication-vs-user-authorization-what-do-they-mean-in-back-end-web-development">check out my blog</a>. I regularly publish articles on software development there.</p>
<p>Thank you for reading and see you soon.</p>
<p><strong>P/S</strong>: If you are learning JavaScript, I created an eBook which teaches 50 topics in JavaScript with hand-drawn digital notes. <a target="_blank" href="https://ubahthebuilder.gumroad.com/l/js-50">Check it out here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Async/Await Tutorial – Learn Callbacks, Promises, and Async/Await in JS by Making Ice Cream 🍧🍨🍦 ]]>
                </title>
                <description>
                    <![CDATA[ Today we're going to build and run an ice cream shop and learn asynchronous JavaScript at the same time. Along the way, you'll learn how to use: Callbacks Promises Async / Await Here's what we'll cover in this article: What is Asynchronous JavaSc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-async-await-tutorial-learn-callbacks-promises-async-await-by-making-icecream/</link>
                <guid isPermaLink="false">66b2095aa5be9a107f4341cd</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joy Shaheb ]]>
                </dc:creator>
                <pubDate>Wed, 02 Jun 2021 14:45:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/FCC-Thumbnail--3-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Today we're going to build and run an <strong>ice cream shop</strong> and learn <strong>asynchronous JavaScript</strong> at the same time. Along the way, you'll learn how to use:</p>
<ul>
<li>Callbacks</li>
<li>Promises</li>
<li>Async / Await</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1j935dg72g9u8zvh2oi.png" alt="Alt Text" width="1107" height="576" loading="lazy"></p>
<h1 id="heading-heres-what-well-cover-in-this-article">Here's what we'll cover in this article:</h1>
<ul>
<li>What is Asynchronous JavaScript?</li>
<li>Synchronous vs Asynchronous JavaScript</li>
<li>How Callbacks Work in JavaScript</li>
<li>How Promises Work in JavaScript</li>
<li>How Async / Await Works in JavaScript</li>
</ul>
<p>So let's dive in!</p>
<h2 id="heading-you-can-watch-this-tutorial-on-youtube-as-well-if-you-like">You can watch this tutorial on YouTube as well if you like:</h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/n5ZtTO1ArWg" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h1 id="heading-what-is-asynchronous-javascript">What is Asynchronous JavaScript?</h1>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7yd96tgxvuowqmfgcx6b.png" alt="Alt Text" width="1498" height="703" loading="lazy"></p>
<p>If you want to build projects efficiently, then this concept is for you.</p>
<p>The theory of async JavaScript helps you break down big complex projects into smaller tasks.</p>
<p>Then you can use any of these three techniques – <strong>callbacks, promises or Async/await</strong> – to run those small tasks in a way that you get the best results.</p>
<p>Let's dive in!🎖️</p>
<h1 id="heading-synchronous-vs-asynchronous-javascript">Synchronous vs Asynchronous JavaScript</h1>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/arzbf1rc3pi4yi6u8wup.png" alt="Alt Text" width="1253" height="642" loading="lazy"></p>
<h2 id="heading-what-is-a-synchronous-system">What is a Synchronous System?</h2>
<p>In a synchronous system, tasks are completed one after another.</p>
<p>Think of this as if you have just one hand to accomplish 10 tasks. So, you have to complete one task at a time.</p>
<p>Take a look at the GIF 👇 – one thing is happening at a time here:</p>
<p><img src="https://media.giphy.com/media/ICIS16DkE9qB9HVxtq/giphy.gif" alt="Synchronous System" width="480" height="258" loading="lazy"></p>
<p>You'll see that until the first image is loaded completely, the second image doesn't start loading.</p>
<p>Well, JavaScript is by default Synchronous <strong>[single threaded]</strong>. Think about it like this – one thread means one hand with which to do stuff.</p>
<h2 id="heading-what-is-an-asynchronous-system">What is an Asynchronous System?</h2>
<p>In this system, tasks are completed independently.</p>
<p>Here, imagine that for 10 tasks, you have 10 hands. So, each hand can do each task independently and at the same time.</p>
<p>Take a look at the GIF 👇 – you can see that each image loads at the same time.</p>
<p><img src="https://media.giphy.com/media/MMDnmJnE7uhX6KtcKc/giphy.gif" alt="Asynchronous System" width="480" height="258" loading="lazy"></p>
<p>Again, all the images are loading at their own pace. None of them is waiting for any of the others.</p>
<h2 id="heading-to-summarize-synchronous-vs-asynchronous-js">To Summarize Synchronous vs Asynchronous JS:</h2>
<p>When three images are on a marathon, in a:</p>
<ul>
<li><strong>Synchronous</strong> system, three images are in the same lane. One can't overtake the other. The race is finished one by one. If image number 2 stops, the following image stops.</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w1r9y4ghhq0t8wjb1u9h.png" alt="Alt Text" width="1544" height="748" loading="lazy"></p>
<ul>
<li><strong>Asynchronous system,</strong> the three images are in different lanes. They'll finish the race on their own pace. Nobody stops for anybody:</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehknx5shc4orh32s0ktk.png" alt="Alt Text" width="1544" height="748" loading="lazy"></p>
<h2 id="heading-synchronous-and-asynchronous-code-examples">Synchronous and Asynchronous Code Examples</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pzbnpcza9rbj8xgiby95.png" alt="Alt Text" width="1156" height="511" loading="lazy"></p>
<p>Before starting our project, let's look at some examples and clear up any doubts.</p>
<h3 id="heading-synchronous-code-example">Synchronous Code Example</h3>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5m6p1qy522lj3auvl5ty.png" alt="Alt Text" width="1054" height="421" loading="lazy"></p>
<p>To test a synchronous system, write this code in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">" I "</span>);

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

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

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

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

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

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

  call_production();
};

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

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

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

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

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

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

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

  call_production();
};

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

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


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

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

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

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

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

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

      resolve( )

    }

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

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

    }

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

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

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

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

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

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

    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    <span class="hljs-keyword">catch</span>(error){
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"customer left"</span>)
    }
}
</code></pre>
<p>And here's the result: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qs9yccq9209u7m9lquju.png" alt="Alt Text" width="1221" height="607" loading="lazy"></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Congratulations for reading until the end! In this article you've learned: </p>
<ul>
<li>The difference between synchronous and asynchronous systems</li>
<li>Mechanisms of asynchronous JavaScript using 3 techniques (callbacks, promises, and Async/ Await)</li>
</ul>
<p>Here's your medal for reading until the end. ❤️</p>
<h3 id="heading-suggestions-and-criticisms-are-highly-appreciated">Suggestions and criticisms are highly appreciated ❤️</h3>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/usxsz1lstuwry3jlly4d.png" alt="Alt Text" width="1000" height="245" loading="lazy"></p>
<p><strong>YouTube <a target="_blank" href="https://youtube.com/c/joyshaheb">/ Joy Shaheb</a></strong></p>
<p><strong>LinkedIn <a target="_blank" href="https://www.linkedin.com/in/joyshaheb/">/ JoyShaheb</a></strong></p>
<p><strong>Twitter <a target="_blank" href="https://twitter.com/JoyShaheb">/ JoyShaheb</a></strong></p>
<p><strong>Instagram <a target="_blank" href="https://www.instagram.com/joyshaheb/">/ JoyShaheb</a></strong></p>
<h1 id="heading-credits">Credits</h1>
<ul>
<li><a target="_blank" href="https://www.freepik.com/user/collections/promises-article/2046500">Collection of all the images used</a></li>
<li><a target="_blank" href="https://www.flaticon.com/packs/unicorn-4">Unicorns</a>, <a target="_blank" href="https://www.flaticon.com/packs/kitty-avatars-3">kitty avatar</a></li>
<li><a target="_blank" href="https://www.pexels.com/photo/brown-tabby-cat-with-slice-of-loaf-bread-on-head-4587955/">tabby cat</a>, <a target="_blank" href="https://www.pexels.com/photo/young-female-astrologist-predicting-future-with-shining-ball-6658693/">Astrologist Woman</a>, <a target="_blank" href="https://www.pexels.com/photo/woman-in-white-dress-holding-white-flower-bouquet-3981511/">girl-holding-flower</a></li>
<li><a target="_blank" href="https://www.vecteezy.com/vector-art/180695-people-mind-emotion-character-cartoon-vector-illustration">Character emotions</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Promise Tutorial – How to Resolve or Reject Promises in JS ]]>
                </title>
                <description>
                    <![CDATA[ Promises are important building blocks for asynchronous operations in JavaScript. You may think that promises are not so easy to understand, learn, and work with. And trust me, you are not alone!  Promises are challenging for many web developers, eve... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-promise-tutorial-how-to-resolve-or-reject-promises-in-js/</link>
                <guid isPermaLink="false">66be0000779f84626329b86a</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tapas Adhikary ]]>
                </dc:creator>
                <pubDate>Tue, 15 Dec 2020 00:49:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/cover-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><code>Promise</code>s are important building blocks for asynchronous operations in JavaScript. You may think that promises are not so easy to understand, learn, and work with. And trust me, you are not alone! </p>
<p>Promises are challenging for many web developers, even after spending years working with them.</p>
<p>In this article, I want to try to change that perception while sharing what I've learned about JavaScript Promises over the last few years. Hope you find it useful.</p>
<h1 id="heading-what-is-a-promise-in-javascript">What is a Promise in JavaScript?</h1>
<p>A <code>Promise</code> is a special JavaScript object. It produces a value after an <code>asynchronous</code> (aka, async) operation completes successfully, or an error if it does not complete successfully due to time out, network error, and so on. </p>
<p>Successful call completions are indicated by the <code>resolve</code> function call, and errors are indicated by the <code>reject</code> function call.</p>
<p>You can create a promise using the promise constructor like this:</p>
<pre><code class="lang-js"><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">// Make an asynchronous call and either resolve or reject</span>
});
</code></pre>
<p>In most cases, a promise may be used for an asynchronous operation. However, technically, you can resolve/reject on both synchronous and asynchronous operations.</p>
<h1 id="heading-hang-on-dont-we-have-callback-functions-for-async-operations">Hang on, don't we have <code>callback</code> functions for async operations?</h1>
<p>Oh, yes! That's right. We have <code>callback</code> functions in JavaScript. But, a callback is not a special thing in JavaScript. It is a regular function that produces results after an <code>asynchronous</code> call completes (with success/error).</p>
<p>The word 'asynchronous' means that something happens in the future, not right now. Usually, callbacks are only used when doing things like network calls, or uploading/downloading things, talking to databases, and so on.</p>
<p>While <code>callbacks</code> are helpful, there is a huge downside to them as well. At times, we may have one callback inside another callback that's in yet another callback and so on. I'm serious! Let's understand this "callback hell" with an example.</p>
<h2 id="heading-how-to-avoid-callback-hell-pizzahub-example">How to Avoid Callback Hell – PizzaHub Example</h2>
<p>Let's order a Veg Margherita pizza 🍕 from the PizzaHub. When we place the order, PizzaHub automatically detects our location, finds a nearby pizza restaurant, and finds if the pizza we are asking for is available. </p>
<p>If it's available, it detects what kind of beverages we get for free along with the pizza, and finally, it places the order. </p>
<p>If the order is placed successfully, we get a message with a confirmation.</p>
<p>So how do we code this using callback functions? I came up with something like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">orderPizza</span>(<span class="hljs-params">type, name</span>) </span>{

    <span class="hljs-comment">// Query the pizzahub for a store</span>
    query(<span class="hljs-string">`/api/pizzahub/`</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result, error</span>)</span>{
       <span class="hljs-keyword">if</span> (!error) {
           <span class="hljs-keyword">let</span> shopId = result.shopId;

           <span class="hljs-comment">// Get the store and query pizzas</span>
           query(<span class="hljs-string">`/api/pizzahub/pizza/<span class="hljs-subst">${shopid}</span>`</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result, error</span>)</span>{
               <span class="hljs-keyword">if</span> (!error) {
                   <span class="hljs-keyword">let</span> pizzas = result.pizzas;

                   <span class="hljs-comment">// Find if my pizza is availavle</span>
                   <span class="hljs-keyword">let</span> myPizza = pizzas.find(<span class="hljs-function">(<span class="hljs-params">pizza</span>) =&gt;</span> {
                       <span class="hljs-keyword">return</span> (pizza.type===type &amp;&amp; pizza.name===name);
                   });

                   <span class="hljs-comment">// Check for the free beverages</span>
                   query(<span class="hljs-string">`/api/pizzahub/beverages/<span class="hljs-subst">${myPizza.id}</span>`</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result, error</span>)</span>{
                       <span class="hljs-keyword">if</span> (!error) {
                           <span class="hljs-keyword">let</span> beverage = result.id;

                           <span class="hljs-comment">// Prepare an order</span>
                           query(<span class="hljs-string">`/api/order`</span>, {<span class="hljs-string">'type'</span>: type, <span class="hljs-string">'name'</span>: name, <span class="hljs-string">'beverage'</span>: beverage}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result, error</span>)</span>{
                              <span class="hljs-keyword">if</span> (!error) {
                                  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Your order of <span class="hljs-subst">${type}</span> <span class="hljs-subst">${name}</span> with <span class="hljs-subst">${beverage}</span> has been placed`</span>);
                              } <span class="hljs-keyword">else</span> {
                                  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Bad luck, No Pizza for you today!`</span>);
                              }
                           });

                       }
                   })
               }
           });
       } 
    });
}

<span class="hljs-comment">// Call the orderPizza method</span>
orderPizza(<span class="hljs-string">'veg'</span>, <span class="hljs-string">'margherita'</span>);
</code></pre>
<p>Let's have a close look at the <code>orderPizza</code> function in the above code. </p>
<p>It calls an API to get your nearby pizza shop's id. After that, it gets the list of pizzas available in that restaurant. It checks if the pizza we are asking for is found and makes another API call to find the beverages for that pizza. Finally the order API places the order.</p>
<p>Here we use a callback for each of the API calls. This leads us to use another callback inside the previous, and so on. </p>
<p>This means we get into something we call (very expressively) <code>Callback Hell</code>. And who wants that? It also forms a code pyramid which is not only confusing but also error-prone.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/callback-hell.png" alt="Image" width="600" height="400" loading="lazy">
<em>Demonstration of callback hell and pyramid</em></p>
<p>There are a few ways to come out of (or not get into) <code>callback hell</code>. The most common one is by using a <code>Promise</code> or <code>async</code> function. However, to understand <code>async</code> functions well, you need to have a fair understanding of <code>Promise</code>s first. </p>
<p>So let's get started and dive into promises.</p>
<h1 id="heading-understanding-promise-states">Understanding Promise States</h1>
<p>Just to review, a promise can be created with the constructor syntax, like this:</p>
<pre><code class="lang-js"><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">// Code to execute</span>
});
</code></pre>
<p>The constructor function takes a function as an argument. This function is called the <code>executor function</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Executor function passed to the </span>
<span class="hljs-comment">// Promise constructor as an argument</span>
<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
    <span class="hljs-comment">// Your logic goes here...</span>
}
</code></pre>
<p>The executor function takes two arguments, <code>resolve</code> and <code>reject</code>. These are the callbacks provided by the JavaScript language. Your logic goes inside the executor function that runs automatically when a <code>new Promise</code> is created.</p>
<p>For the promise to be effective, the executor function should call either of the callback functions, <code>resolve</code> or <code>reject</code>. We will learn more about this in detail in a while.</p>
<p>The <code>new Promise()</code> constructor returns a <code>promise</code> object. As the executor function needs to handle async operations, the returned promise object should be capable of informing when the execution has been started, completed (resolved) or retuned with error (rejected). </p>
<p>A <code>promise</code> object has the following internal properties:</p>
<ol>
<li><p><code>state</code> – This property can have the following values:</p>
</li>
<li><p><code>pending</code>: Initially when the executor function starts the execution.</p>
</li>
<li><code>fulfilled</code>: When the promise is resolved.</li>
<li><code>rejected</code>: When the promise is rejected.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/states_1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Promise states</em></p>
<ol start="2">
<li><p><code>result</code> – This property can have the following values:</p>
</li>
<li><p><code>undefined</code>: Initially when the <code>state</code> value is <code>pending</code>.</p>
</li>
<li><code>value</code>: When <code>resolve(value)</code> is called.</li>
<li><code>error</code>: When <code>reject(error)</code> is called.</li>
</ol>
<p>These internal properties are code-inaccessible but they are inspectable. This means that we will be able to inspect the <code>state</code> and <code>result</code> property values using the debugger tool, but we will not be able to access them directly using the program.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/promise_state_inspect.png" alt="Image" width="600" height="400" loading="lazy">
<em>Able to inspect the internal properties of a promise</em></p>
<p>A promise's state can be <code>pending</code>, <code>fulfilled</code> or <code>rejected</code>. A promise that is either resolved or rejected is called <code>settled</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/states_2.png" alt="Image" width="600" height="400" loading="lazy">
<em>A settled promise is either fulfilled or rejected</em></p>
<h3 id="heading-how-promises-are-resolved-and-rejected">How promises are resolved and rejected</h3>
<p>Here is an example of a promise that will be resolved (<code>fulfilled</code> state) with the value <code>I am done</code> immediately.</p>
<pre><code class="lang-js"><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>{
    resolve(<span class="hljs-string">"I am done"</span>);
});
</code></pre>
<p> The promise below will be rejected (<code>rejected</code> state) with the error message <code>Something is not right!</code>.</p>
<pre><code class="lang-js"><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>{
    reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Something is not right!'</span>));
});
</code></pre>
<p>An important point to note:</p>
<blockquote>
<p>A Promise executor should call only one <code>resolve</code> or one <code>reject</code>. Once one state is changed (pending =&gt; fulfilled or pending =&gt; rejected), that's all. Any further calls to <code>resolve</code> or <code>reject</code> will be ignored.</p>
</blockquote>
<pre><code class="lang-js"><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>{
  resolve(<span class="hljs-string">"I am surely going to get resolved!"</span>);

  reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Will this be ignored?'</span>)); <span class="hljs-comment">// ignored</span>
  resolve(<span class="hljs-string">"Ignored?"</span>); <span class="hljs-comment">// ignored</span>
});
</code></pre>
<p>In the example above, only the first one to resolve will be called and the rest will be ignored.</p>
<h1 id="heading-how-to-handle-a-promise-once-youve-created-it">How to handle a Promise once you've created it</h1>
<p>A <code>Promise</code> uses an executor function to complete a task (mostly asynchronously). A consumer function (that uses an outcome of the promise) should get notified when the executor function is done with either resolving (success) or rejecting (error).</p>
<p>The handler methods, <code>.then()</code>, <code>.catch()</code> and <code>.finally()</code>, help to create the link between the executor and the consumer functions so that they can be in sync when a promise <code>resolve</code>s or <code>reject</code>s.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/consumer_executor.png" alt="Image" width="600" height="400" loading="lazy">
<em>The executor and consumer functions</em></p>
<h2 id="heading-how-to-use-the-then-promise-handler">How to Use the <code>.then()</code> Promise Handler</h2>
<p>The <code>.then()</code> method should be called on the promise object to handle a result (resolve) or an error (reject). </p>
<p>It accepts two functions as parameters. Usually, the <code>.then()</code> method should be called from the consumer function where you would like to know the outcome of a promise's execution.</p>
<pre><code class="lang-js">promise.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-function">(<span class="hljs-params">error</span>) =&gt;</span> { 
     <span class="hljs-built_in">console</span>.log(error);
  }
);
</code></pre>
<p>If you are interested only in successful outcomes, you can just pass one argument to it, like this:</p>
<pre><code class="lang-js">promise.then(
  <span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> { 
      <span class="hljs-built_in">console</span>.log(result);
  }
);
</code></pre>
<p>If you are interested only in the error outcome, you can pass <code>null</code> for the first argument, like this:</p>
<pre><code class="lang-js">promise.then(
  <span class="hljs-literal">null</span>,
  <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> { 
      <span class="hljs-built_in">console</span>.log(error)
  }
);
</code></pre>
<p>However, you can handle errors in a better way using the <code>.catch()</code> method that we will see in a minute.</p>
<p>Let's look at a couple of examples of handling results and errors using the <code>.then</code> and <code>.catch</code> handlers. We will make this learning a bit more fun with a few real asynchronous requests. We will use the <a target="_blank" href="https://pokeapi.co/">PokeAPI</a> to get information about Pokémon and resolve/reject them using Promises.</p>
<p>First, let us create a generic function that accepts a PokeAPI URL as argument and returns a Promise. If the API call is successful, a resolved promise is returned. A rejected promise is returned for any kind of errors. </p>
<p>We will be using this function in several examples from now on to get a promise and work on it.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPromise</span>(<span class="hljs-params">URL</span>) </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-keyword">let</span> req = <span class="hljs-keyword">new</span> XMLHttpRequest();
    req.open(<span class="hljs-string">"GET"</span>, URL);
    req.onload = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">if</span> (req.status == <span class="hljs-number">200</span>) {
        resolve(req.response);
      } <span class="hljs-keyword">else</span> {
        reject(<span class="hljs-string">"There is an Error!"</span>);
      }
    };
    req.send();
  });
  <span class="hljs-keyword">return</span> promise;
}
</code></pre>
<p>Example 1: Get 50 Pokémon's information:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ALL_POKEMONS_URL = <span class="hljs-string">'https://pokeapi.co/api/v2/pokemon?limit=50'</span>;

<span class="hljs-comment">// We have discussed this function already!</span>
<span class="hljs-keyword">let</span> promise = getPromise(ALL_POKEMONS_URL);

<span class="hljs-keyword">const</span> consumer = <span class="hljs-function">() =&gt;</span> {
    promise.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">// Log the result of 50 Pokemons</span>
        },
        <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
            <span class="hljs-comment">// As the URL is a valid one, this will not be called.</span>
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'We have encountered an Error!'</span>); <span class="hljs-comment">// Log an error</span>
    });
}

consumer();
</code></pre>
<p>Example 2: Let's try an invalid URL</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> POKEMONS_BAD_URL = <span class="hljs-string">'https://pokeapi.co/api/v2/pokemon-bad/'</span>;

<span class="hljs-comment">// This will reject as the URL is 404</span>
<span class="hljs-keyword">let</span> promise = getPromise(POKEMONS_BAD_URL);

<span class="hljs-keyword">const</span> consumer = <span class="hljs-function">() =&gt;</span> {
    promise.then(
        <span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
            <span class="hljs-comment">// The promise didn't resolve. Hence, it will</span>
            <span class="hljs-comment">// not be executed.</span>
            <span class="hljs-built_in">console</span>.log({result});
        },
        <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
            <span class="hljs-comment">// A rejected prmise will execute this</span>
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'We have encountered an Error!'</span>); <span class="hljs-comment">// Log an error</span>
        }
    );
}

consumer();
</code></pre>
<h2 id="heading-how-to-use-the-catch-promise-handler">How to Use the <code>.catch()</code> Promise Handler</h2>
<p>You can use this handler method to handle errors (rejections) from promises. The syntax of passing <code>null</code> as the first argument to the <code>.then()</code> is not a great way to handle errors. So we have <code>.catch()</code> to do the same job with some neat syntax:</p>
<pre><code class="lang-js"><span class="hljs-comment">// This will reject as the URL is 404</span>
<span class="hljs-keyword">let</span> promise = getPromise(POKEMONS_BAD_URL);

<span class="hljs-keyword">const</span> consumer = <span class="hljs-function">() =&gt;</span> {
    promise.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
}

consumer();
</code></pre>
<p>If we throw an Error like <code>new Error("Something wrong!")</code>  instead of calling the <code>reject</code> from the promise executor and handlers, it will still be treated as a rejection. It means that this will be caught by the <code>.catch</code> handler method. </p>
<p>This is the same for any <em>synchronous</em> exceptions that happen in the promise executor and handler functions.</p>
<p>Here is an example where it will be treated like a reject and the <code>.catch</code> handler method will be called:</p>
<pre><code class="lang-js"><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">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Something is wrong!"</span>);<span class="hljs-comment">// No reject call</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>
<h2 id="heading-how-to-use-the-finally-promise-handler">How to Use the <code>.finally()</code> Promise Handler</h2>
<p>The <code>.finally()</code> handler performs cleanups like stopping a loader, closing a live connection, and so on. The <code>finally()</code> method will be called irrespective of whether a promise <code>resolve</code>s or <code>reject</code>s. It passes through the result or error to the next handler which can call a .then() or .catch() again.</p>
<p>Here is an example that'll help you understand all three methods together:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> loading = <span class="hljs-literal">true</span>;
loading &amp;&amp; <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Loading...'</span>);

<span class="hljs-comment">// Gatting Promise</span>
promise = getPromise(ALL_POKEMONS_URL);

promise.finally(<span class="hljs-function">() =&gt;</span> {
    loading = <span class="hljs-literal">false</span>;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Promise Settled and loading is <span class="hljs-subst">${loading}</span>`</span>);
}).then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log({result});
}).catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(error)
});
</code></pre>
<p>To explain a bit further:</p>
<ul>
<li>The <code>.finally()</code> method makes loading <code>false</code>.</li>
<li>If the promise resolves, the <code>.then()</code> method will be called. If the promise rejects with an error, the <code>.catch()</code> method will be called. The <code>.finally()</code> will be called irrespective of the resolve or reject.</li>
</ul>
<h1 id="heading-what-is-the-promise-chain">What is the Promise Chain?</h1>
<p>The  <code>promise.then()</code> call always returns a promise. This promise will have the <code>state</code> as <code>pending</code> and <code>result</code> as <code>undefined</code>. It allows us to call the next <code>.then</code> method on the new promise.</p>
<p>When the first <code>.then</code> method returns a value, the next <code>.then</code> method can receive that. The second one can now pass to the third <code>.then()</code> and so on. This forms a chain of <code>.then</code> methods to pass the promises down. This phenomenon is called the <code>Promise Chain</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/image-105.png" alt="Image" width="600" height="400" loading="lazy">
<em>Promise Chain</em></p>
<p>Here is an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> promise = getPromise(ALL_POKEMONS_URL);

promise.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
    <span class="hljs-keyword">let</span> onePokemon = <span class="hljs-built_in">JSON</span>.parse(result).results[<span class="hljs-number">0</span>].url;
    <span class="hljs-keyword">return</span> onePokemon;
}).then(<span class="hljs-function"><span class="hljs-params">onePokemonURL</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(onePokemonURL);
}).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">'In the catch'</span>, error);
});
</code></pre>
<p>Here we first get a promise resolved and then extract the URL to reach the first Pokémon. We then return that value and it will be passed as a promise to the next .then() handler function. Hence the output,</p>
<pre><code class="lang-shell">https://pokeapi.co/api/v2/pokemon/1/
</code></pre>
<p>The <code>.then</code> method can return either:</p>
<ul>
<li>A value (we have seen this already)</li>
<li>A brand new promise.</li>
</ul>
<p>It can also throw an error.</p>
<p>Here is an example where we have created a promise chain with the <code>.then</code> methods which returns results and a new promise:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Promise Chain with multiple then and catch</span>
<span class="hljs-keyword">let</span> promise = getPromise(ALL_POKEMONS_URL);

promise.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
    <span class="hljs-keyword">let</span> onePokemon = <span class="hljs-built_in">JSON</span>.parse(result).results[<span class="hljs-number">0</span>].url;
    <span class="hljs-keyword">return</span> onePokemon;
}).then(<span class="hljs-function"><span class="hljs-params">onePokemonURL</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(onePokemonURL);
    <span class="hljs-keyword">return</span> getPromise(onePokemonURL);
}).then(<span class="hljs-function"><span class="hljs-params">pokemon</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">JSON</span>.parse(pokemon));
}).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">'In the catch'</span>, error);
});
</code></pre>
<p>In the first <code>.then</code> call we extract the URL and return it as a value. This URL will be passed to the second <code>.then</code> call where we are returning a new promise taking that URL as an argument. </p>
<p>This promise will be resolved and passed down to the chain where we get the information about the Pokémon. Here is the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/image-159.png" alt="Image" width="600" height="400" loading="lazy">
<em>Output of the promise chain call</em></p>
<p>In case there is an error or a promise rejection, the .catch method in the chain will be called.</p>
<p>A point to note: Calling <code>.then</code> multiple times doesn't form a Promise chain. You may end up doing something like this only to introduce a bug in the code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> promise = getPromise(ALL_POKEMONS_URL);

promise.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
    <span class="hljs-keyword">let</span> onePokemon = <span class="hljs-built_in">JSON</span>.parse(result).results[<span class="hljs-number">0</span>].url;
    <span class="hljs-keyword">return</span> onePokemon;
});
promise.then(<span class="hljs-function"><span class="hljs-params">onePokemonURL</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(onePokemonURL);
    <span class="hljs-keyword">return</span> getPromise(onePokemonURL);
});
promise.then(<span class="hljs-function"><span class="hljs-params">pokemon</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">JSON</span>.parse(pokemon));
});
</code></pre>
<p>We call the <code>.then</code> method three times on the same promise, but we don't pass the promise down. This is different than the promise chain. In the above example, the output will be an error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/image-160.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-how-to-handle-multiple-promises">How to Handle Multiple Promises</h1>
<p>Apart from the handler methods (.then, .catch, and .finally), there are six static methods available in the Promise API. The first four methods accept an array of promises and run them in parallel.</p>
<ol>
<li>Promise.all</li>
<li>Promise.any</li>
<li>Promise.allSettled</li>
<li>Promise.race</li>
<li>Promise.resolve</li>
<li>Promise.reject</li>
</ol>
<p>Let's go through each one.</p>
<h2 id="heading-the-promiseall-method">The Promise.all() method</h2>
<p><code>Promise.all([promises])</code> accepts a collection (for example, an array) of promises as an argument and executes them in parallel. </p>
<p>This method waits for all the promises to resolve and returns the array of promise results. If any of the promises reject or execute to fail due to an error, all other promise results will be ignored.</p>
<p>Let's create three promises to get information about three Pokémons.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> BULBASAUR_POKEMONS_URL = <span class="hljs-string">'https://pokeapi.co/api/v2/pokemon/bulbasaur'</span>;
<span class="hljs-keyword">const</span> RATICATE_POKEMONS_URL = <span class="hljs-string">'https://pokeapi.co/api/v2/pokemon/raticate'</span>;
<span class="hljs-keyword">const</span> KAKUNA_POKEMONS_URL = <span class="hljs-string">'https://pokeapi.co/api/v2/pokemon/kakuna'</span>;


<span class="hljs-keyword">let</span> promise_1 = getPromise(BULBASAUR_POKEMONS_URL);
<span class="hljs-keyword">let</span> promise_2 = getPromise(RATICATE_POKEMONS_URL);
<span class="hljs-keyword">let</span> promise_3 = getPromise(KAKUNA_POKEMONS_URL);
</code></pre>
<p>Use the Promise.all() method by passing an array of promises. </p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.all([promise_1, promise_2, promise_3]).then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log({result});
}).catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'An Error Occured'</span>);
});
</code></pre>
<p>Output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/image-161.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you see in the output, the result of all the promises is returned. The time to execute all the promises is equal to the max time the promise takes to run.</p>
<h2 id="heading-the-promiseany-method">The Promise.any() method</h2>
<p><code>Promise.any([promises])</code> - Similar to the <code>all()</code> method, <code>.any()</code> also accepts an array of promises to execute them in parallel. This method doesn't wait for all the promises to resolve. It is done when any one of the promises is settled.</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">Promise</span>.any([promise_1, promise_2, promise_3]).then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">JSON</span>.parse(result));
 }).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">'An Error Occured'</span>);
 });
</code></pre>
<p>The output would be the result of any of the resolved promises:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/image-162.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-promiseallsettled-method">The Promise.allSettled() method</h2>
<p><code>romise.allSettled([promises])</code> - This method waits for all promises to settle(resolve/reject) and returns their results as an array of objects. The results will contain a state (fulfilled/rejected) and value, if fulfilled. In case of rejected status, it will return a reason for the error.</p>
<p>Here is an example of all fulfilled promises:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.allSettled([promise_1, promise_2, promise_3]).then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log({result});
}).catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'There is an Error!'</span>);
});
</code></pre>
<p>Output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/image-163.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If any of the promises rejects, say, the promise_1,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> promise_1 = getPromise(POKEMONS_BAD_URL);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/image-164.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-promiserace-method">The Promise.race() method</h2>
<p><code>Promise.race([promises])</code> – It waits for the first (quickest) promise to settle, and returns the result/error accordingly.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Promise</span>.race([promise_1, promise_2, promise_3]).then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">JSON</span>.parse(result));
}).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">'An Error Occured'</span>);
});
</code></pre>
<p>Output the fastest promise that got resolved:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/image-165.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-promiseresolvereject-methods">The Promise.resolve/reject methods</h2>
<p><code>Promise.resolve(value)</code> – It resolves a promise with the value passed to it. It is the same as the following:</p>
<pre><code class="lang-js"><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-params">resolve</span> =&gt;</span> resolve(value));
</code></pre>
<p><code>Promise.reject(error)</code> – It rejects a promise with the error passed to it. It is the same as the following:</p>
<pre><code class="lang-js"><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-params">resolve, reject</span>) =&gt;</span> reject(error));
</code></pre>
<h1 id="heading-can-we-rewrite-the-pizzahub-example-with-promises">Can we rewrite the PizzaHub example with Promises?</h1>
<p>Sure, let's do it. Let us assume that the <code>query</code> method will return a promise. Here is an example query() method. In real life, this method may talk to a database and return results. In this case, it is very much hard-coded but serves the same purpose.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">query</span>(<span class="hljs-params">endpoint</span>) </span>{
  <span class="hljs-keyword">if</span> (endpoint === <span class="hljs-string">`/api/pizzahub/`</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> {
      resolve({<span class="hljs-string">'shopId'</span>: <span class="hljs-string">'123'</span>});
    })
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (endpoint.indexOf(<span class="hljs-string">'/api/pizzahub/pizza/'</span>) &gt;=<span class="hljs-number">0</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> {
      resolve({<span class="hljs-attr">pizzas</span>: [{<span class="hljs-string">'type'</span>: <span class="hljs-string">'veg'</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'margherita'</span>, <span class="hljs-string">'id'</span>: <span class="hljs-string">'123'</span>}]});
    })
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (endpoint.indexOf(<span class="hljs-string">'/api/pizzahub/beverages'</span>) &gt;=<span class="hljs-number">0</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> {
      resolve({<span class="hljs-attr">id</span>: <span class="hljs-string">'10'</span>, <span class="hljs-string">'type'</span>: <span class="hljs-string">'veg'</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'margherita'</span>, <span class="hljs-string">'beverage'</span>: <span class="hljs-string">'coke'</span>});
    })
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (endpoint === <span class="hljs-string">`/api/order`</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> {
      resolve({<span class="hljs-string">'type'</span>: <span class="hljs-string">'veg'</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'margherita'</span>, <span class="hljs-string">'beverage'</span>: <span class="hljs-string">'coke'</span>});
    })
  }
}
</code></pre>
<p>Next is the refactoring of our <code>callback hell</code>. To do that, first, we will create a few logical functions:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Returns a shop id</span>
<span class="hljs-keyword">let</span> getShopId = <span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.shopId;

<span class="hljs-comment">// Returns a promise with pizza list for a shop</span>
<span class="hljs-keyword">let</span> getPizzaList = <span class="hljs-function"><span class="hljs-params">shopId</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> url = <span class="hljs-string">`/api/pizzahub/pizza/<span class="hljs-subst">${shopId}</span>`</span>;
  <span class="hljs-keyword">return</span> query(url);
}

<span class="hljs-comment">// Returns a promise with pizza that matches the customer request</span>
<span class="hljs-keyword">let</span> getMyPizza = <span class="hljs-function">(<span class="hljs-params">result, type, name</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> pizzas = result.pizzas;
  <span class="hljs-keyword">let</span> myPizza = pizzas.find(<span class="hljs-function">(<span class="hljs-params">pizza</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> (pizza.type===type &amp;&amp; pizza.name===name);
  });
  <span class="hljs-keyword">const</span> url = <span class="hljs-string">`/api/pizzahub/beverages/<span class="hljs-subst">${myPizza.id}</span>`</span>;
  <span class="hljs-keyword">return</span> query(url);
}

<span class="hljs-comment">// Returns a promise after Placing the order</span>
<span class="hljs-keyword">let</span> performOrder = <span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
  <span class="hljs-keyword">let</span> beverage = result.id;
   <span class="hljs-keyword">return</span> query(<span class="hljs-string">`/api/order`</span>, {<span class="hljs-string">'type'</span>: result.type, <span class="hljs-string">'name'</span>: result.name, <span class="hljs-string">'beverage'</span>: result.beverage});
}

<span class="hljs-comment">// Confirm the order</span>
<span class="hljs-keyword">let</span> confirmOrder = <span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Your order of <span class="hljs-subst">${result.type}</span> <span class="hljs-subst">${result.name}</span> with <span class="hljs-subst">${result.beverage}</span> has been placed!`</span>);
}
</code></pre>
<p>Use these functions to create the required promises. This is where you should compare with the <code>callback hell</code> example. This is so nice and elegant.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">orderPizza</span>(<span class="hljs-params">type, name</span>) </span>{
  query(<span class="hljs-string">`/api/pizzahub/`</span>)
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> getShopId(result))
  .then(<span class="hljs-function"><span class="hljs-params">shopId</span> =&gt;</span> getPizzaList(shopId))
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> getMyPizza(result, type, name))
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> performOrder(result))
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> confirmOrder(result))
  .catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Bad luck, No Pizza for you today!`</span>);
  })
}
</code></pre>
<p>Finally, call the orderPizza() method by passing the pizza type and name, like this:</p>
<pre><code class="lang-js">orderPizza(<span class="hljs-string">'veg'</span>, <span class="hljs-string">'margherita'</span>);
</code></pre>
<h1 id="heading-whats-next-from-here">What's next from here?</h1>
<p>If you are here and have read through most of the lines above, congratulations! You should now have a better grip of JavaScript Promises. All the examples used in this article are in this <a target="_blank" href="https://github.com/atapas/js-promise-example">GitHub repository</a>. </p>
<p>Next, you should learn about the <code>async</code> function in JavaScript which simplifies things further. The concept of JavaScript promises is best learned by writing small examples and building on top of them. </p>
<p>Irrespective of the framework or library (Angular, React, Vue, and so on) we use, async operations are unavoidable. This means that we have to understand promises to make things work better. </p>
<p>Also, I'm sure you will find the usage of the <code>fetch</code> method much easier now:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'/api/user.json'</span>)
.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">response</span>) </span>{
    <span class="hljs-keyword">return</span> response.json();
})
.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">json</span>) </span>{
    <span class="hljs-built_in">console</span>.log(json); <span class="hljs-comment">// {"name": "tapas", "blog": "freeCodeCamp"}</span>
});
</code></pre>
<ul>
<li>The <code>fetch</code> method returns a promise. So we can call the <code>.then</code> handler method on it.</li>
<li>The rest is about the promise chain which we learned in this article.</li>
</ul>
<h1 id="heading-before-we-end">Before we end...</h1>
<p>Thank you for reading this far! Let's connect. You can @ me on <a target="_blank" href="https://twitter.com/tapasadhikary">Twitter (@tapasadhikary)</a> with comments.</p>
<p>You may also like these other articles:</p>
<ul>
<li><a target="_blank" href="https://blog.greenroots.info/javascript-undefined-and-null-lets-talk-about-it-one-last-time-ckh64kmz807v848s15kdkg3dd">JavaScript undefined and null: Let's talk about it one last time!</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/javascript-equality-comparison-with-and-objectis-ckdpt2ryk01vel9s186ft8cwl">JavaScript: Equality comparison with ==, === and Object.is</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/javascript-this-keyword-binding-rules/">The JavaScript <code>this</code> Keyword + 5 Key Binding Rules Explained for JS Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/javascript-typeof-how-to-check-the-type-of-a-variable-or-object-in-js/">JavaScript TypeOf – How to Check the Type of a Variable or Object in JS</a></li>
</ul>
<p>That's all for now. See you again with my next article soon. Until then, please take good care of yourself.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Modern JavaScript – Imports, Exports, Let, Const, and Promises in ES6+ ]]>
                </title>
                <description>
                    <![CDATA[ Over the past few years, there have been many updates to the JavaScript language. And these updates are very useful if you want to improve your coding. ​Keeping abreast of the newest developments in the language is really important. It can help you g... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-modern-javascript/</link>
                <guid isPermaLink="false">66bc5527d94fa6cb67b84502</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Yogesh Chavan ]]>
                </dc:creator>
                <pubDate>Mon, 07 Dec 2020 22:47:10 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5fcb4bbce6787e098393a6fd.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Over the past few years, there have been many updates to the JavaScript language. And these updates are very useful if you want to improve your coding.</p>
<p>​Keeping abreast of the newest developments in the language is really important. It can help you get a higher paying job, keep up to date with the latest trends, improve your code quality, and excel in your current job.</p>
<p>And you definitely need to know the latest features if you're trying to learn a JavaScript library like React or framework like Angular or Vue.</p>
<p>Recently, there have been many useful additions to JavaScript like the <strong>Nullish coalescing operator</strong>, <strong>optional chaining</strong>, <strong>Promises</strong>, <strong>async/await</strong>, <strong>ES6 destructuring</strong>, and more.</p>
<p>So today, we will look at some of these concepts which every JavaScript developer should be aware of.</p>
<p>Let's get started and dive into the things you need to know about JS.</p>
<h2 id="heading-let-and-const-in-javascript">Let and const in JavaScript</h2>
<p>Before ES6, JavaScript used the <code>var</code> keyword which only used function and global scope. There was no block-level scope.</p>
<p>With the addition of <code>let</code> and <code>const</code> JavaScript added block scoping.</p>
<h3 id="heading-how-to-use-let-in-javascript">How to use let in JavaScript</h3>
<p>When we declare a variable using the <code>let</code> keyword, we can <strong>assign</strong> a new value to that variable later but we cannot <strong>re-declare</strong> it with the same name.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>
<span class="hljs-keyword">var</span> value = <span class="hljs-number">10</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 10</span>

<span class="hljs-keyword">var</span> value = <span class="hljs-string">"hello"</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// hello</span>

<span class="hljs-keyword">var</span> value = <span class="hljs-number">30</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 30</span>
</code></pre>
<p>As you can see above, we have re-declared the variable <code>value</code> using the <code>var</code> keyword multiple times.</p>
<p>Before ES6, we were able to re-declare a variable that had already been declared before if it wasn't used meaningfully and was instead causing confusion.</p>
<p>But what if we already had a variable declared with the same name somewhere else and we're re-declaring it without realizing it? Then we might override the variable value, causing some difficult to debug issues.</p>
<p>So when you use the <code>let</code> keyword, you will get an error when you try to re-declare the variable with the same name – which is a good thing.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">let</span> value = <span class="hljs-number">10</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 10</span>

<span class="hljs-keyword">let</span> value = <span class="hljs-string">"hello"</span>; <span class="hljs-comment">// Uncaught SyntaxError: Identifier 'value' has already been declared</span>
</code></pre>
<p>But, the following code is valid:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">let</span> value = <span class="hljs-number">10</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 10</span>

value = <span class="hljs-string">"hello"</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// hello</span>
</code></pre>
<p>We don't get an error in the above code because we're <strong>re-assigning</strong> a new value to the  <code>value</code> variable. But we're <strong>not re-declaring</strong> <code>value</code> again.</p>
<p>Now, take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>
<span class="hljs-keyword">var</span> isValid = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">if</span>(isValid) {
  <span class="hljs-keyword">var</span> number = <span class="hljs-number">10</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, number); <span class="hljs-comment">// inside: 10</span>
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, number); <span class="hljs-comment">// outside: 10</span>
</code></pre>
<p>As you can see in this code, when we declare a variable with the <code>var</code> keyword, it's available outside the <code>if</code> block also.</p>
<p>Now take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">let</span> isValid = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">if</span>(isValid) {
  <span class="hljs-keyword">let</span> number = <span class="hljs-number">10</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, number); <span class="hljs-comment">// inside: 10</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, number); <span class="hljs-comment">// Uncaught ReferenceError: number is not defined</span>
</code></pre>
<p>As you can see, the <code>number</code> variable when declared using the <code>let</code> keyword is only accessible inside the <code>if</code> block. Outside the block it's not available, so we got a reference error when we tried to access it outside the <code>if</code> block.</p>
<p>But if there is a <code>number</code> variable outside the <code>if</code> block, then it will work as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">let</span> isValid = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">let</span> number = <span class="hljs-number">20</span>;

<span class="hljs-keyword">if</span>(isValid) {
  <span class="hljs-keyword">let</span> number = <span class="hljs-number">10</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, number); <span class="hljs-comment">// inside: 10</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, number); <span class="hljs-comment">// outside: 20</span>
</code></pre>
<p>Here, we have two <code>number</code> variables in a separate scope. So outside the <code>if</code> block, the value of <code>number</code> will be 20.</p>
<p>Take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++){
 <span class="hljs-built_in">console</span>.log(i);
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, i); <span class="hljs-comment">// 10</span>
</code></pre>
<p>When using the <code>var</code> keyword, <code>i</code> is available even outside the <code>for</code> loop.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES6 Code</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++){
 <span class="hljs-built_in">console</span>.log(i);
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, i); <span class="hljs-comment">// Uncaught ReferenceError: i is not defined</span>
</code></pre>
<p>But when using the <code>let</code> keyword, it's not available outside the loop.</p>
<p>So as you can see from the above code samples, using <code>let</code> makes the variable available only inside that block and it's not accessible outside the block.</p>
<p>We can also create a block by a pair of curly brackets like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> i = <span class="hljs-number">10</span>;
{
 <span class="hljs-keyword">let</span> i = <span class="hljs-number">20</span>;
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, i); <span class="hljs-comment">// inside: 20</span>
 i = <span class="hljs-number">30</span>;
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'i again:'</span>, i); <span class="hljs-comment">// i again: 30</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, i); <span class="hljs-comment">// outside: 10</span>
</code></pre>
<p>If you remember, I said we cannot re-declare a <code>let</code> based variable in the same block but we can re-declare it in another block. As you can see in the above code, we have re-declared <code>i</code> and assigned a new value of <code>20</code> inside the block. Once declared, that variable value will be available only in that block.</p>
<p>Outside the block, when we printed that variable, we got <code>10</code> instead of the previously assigned value of <code>30</code> because outside the block, the inside <code>i</code> variable does not exist.</p>
<p>If we don't have the variable <code>i</code> declared outside, then we'll get an error as you can see in the below code:</p>
<pre><code class="lang-js">{
 <span class="hljs-keyword">let</span> i = <span class="hljs-number">20</span>;
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside:'</span>, i); <span class="hljs-comment">// inside: 20</span>
 i = <span class="hljs-number">30</span>;
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'i again:'</span>, i); <span class="hljs-comment">// i again: 30</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'outside:'</span>, i); <span class="hljs-comment">// Uncaught ReferenceError: i is not defined</span>
</code></pre>
<h3 id="heading-how-to-use-const-in-javascript">How to use const in JavaScript</h3>
<p>The <code>const</code> keyword works exactly the same as the <code>let</code> keyword in its block scoping functionality. So let's look at how they differ from each other.</p>
<p>When we declare a variable as <code>const</code>, it's considered a constant variable whose value will never change.</p>
<p>In the case of <code>let</code>, we're able to assign a new value to that variable later like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> number = <span class="hljs-number">10</span>;
number = <span class="hljs-number">20</span>;

<span class="hljs-built_in">console</span>.log(number); <span class="hljs-comment">// 20</span>
</code></pre>
<p>But we can't do that in case of <code>const</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> number = <span class="hljs-number">10</span>;
number = <span class="hljs-number">20</span>; <span class="hljs-comment">// Uncaught TypeError: Assignment to constant variable.</span>
</code></pre>
<p>We can't even <strong>re-declare</strong> a <code>const</code> variable.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> number = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(number); <span class="hljs-comment">// 20</span>

<span class="hljs-keyword">const</span> number = <span class="hljs-number">10</span>; <span class="hljs-comment">// Uncaught SyntaxError: Identifier 'number' has already been declared</span>
</code></pre>
<p>Now, take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];

arr.push(<span class="hljs-number">5</span>);

<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
</code></pre>
<p>We said that the <code>const</code> variable is constant whose value will never change – but we have changed the constant array above. So how does that make sense?</p>
<blockquote>
<p>Note: Arrays are reference types and not primitive types in JavaScript</p>
</blockquote>
<p>So what actually gets stored in <code>arr</code> is not the actual array but only the reference (address) of the memory location where the actual array is stored.</p>
<p>So by doing <code>arr.push(5);</code> we're not actually changing the reference where the <code>arr</code> points to, but we're changing the values stored at that reference.</p>
<p>The same is the case with objects:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = {
 <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>,
 <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>
};

obj.age = <span class="hljs-number">40</span>;

<span class="hljs-built_in">console</span>.log(obj); <span class="hljs-comment">// { name: 'David', age: 40 }</span>
</code></pre>
<p>Here, also we're not changing the reference of where the <code>obj</code> points to but we're changing the values stored at that reference.</p>
<p>So the above code will work, but the below code will not work.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Mike'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">40</span> };
obj = obj1; <span class="hljs-comment">// Uncaught TypeError: Assignment to constant variable.</span>
</code></pre>
<p>The above code does not work because we're trying to change the reference that the  <code>const</code> variable points to.</p>
<p>So the key point to remember when using const is that, when we declare a variable as a constant using const we cannot re-define it. We also cannot re-assign that variable, but we can change the values stored at that location if the variable is of reference type.</p>
<p>So the below code is invalid because we're re-assigning a new value to it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
arr = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>]; <span class="hljs-comment">// Uncaught TypeError: Assignment to constant variable.</span>
</code></pre>
<p>But note that we can change the values inside the array, as we saw previously.</p>
<p>The following code of re-defining a <code>const</code> variable is also invalid.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> name = <span class="hljs-string">"David"</span>;
<span class="hljs-keyword">const</span> name = <span class="hljs-string">"Raj"</span>; <span class="hljs-comment">// Uncaught SyntaxError: Identifier 'name' has already been declared</span>
</code></pre>
<h3 id="heading-let-and-const-wrap-up">let and const wrap up</h3>
<ul>
<li>The keywords <code>let</code> and <code>const</code> add block scoping in JavaScript.</li>
<li>When we declare a variable as <code>let</code>, we cannot <code>re-define</code> or <code>re-declare</code> another let variable with the same name in the same scope (function or block scope) but we can <code>re-assign</code> a value to it.</li>
<li>When we declare a variable as <code>const</code>, we cannot <code>re-define</code> or <code>re-declare</code> another <code>const</code> variable with the same name in the same scope (function or block scope). But we can change the values stored in that variable if the variable is of a reference type like an array or object.</li>
</ul>
<p>Alright, let's move on to the next big topic: promises.</p>
<h2 id="heading-promises-in-javascript">Promises in JavaScript</h2>
<p>Promises are one of the most important yet confusing and difficult to understand part of JavaScript. And most new devs, as well as experienced ones, struggle to understand them.</p>
<p>Promises were added in ES6 as a native implementation.</p>
<p>So what is a promise? A promise represents an asynchronous operation to be completed in the future.</p>
<p>Previously, Before ES6, there was no way to wait for something to perform some operation.</p>
<p>For example, when we wanted to make an API call, there was no way to wait until the results came back before ES6.</p>
<p>For that, we used to use external libraries like Jquery or Ajax which had their own implementation of promises. But there was no browser implemented promise thing.</p>
<p>But now using Promises in ES6, we can make an API call ourselves and wait until it's done to perform some operation.</p>
<h3 id="heading-how-to-create-a-promise">How to create a Promise</h3>
<p>To create a promise we need to use the <code>Promise</code> constructor function like this:</p>
<pre><code class="lang-js"><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-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{

});
</code></pre>
<p>The <code>Promise</code> constructor takes a function as an argument and that function internally receives <code>resolve</code> and <code>reject</code> as parameters.</p>
<p>The <code>resolve</code> and <code>reject</code> parameters are actually functions that we can call depending on the outcome of the asynchronous operation.</p>
<p>A <code>Promise</code> goes through three states:</p>
<ul>
<li>Pending</li>
<li>Fulfilled</li>
<li>Rejected</li>
</ul>
<p>When we create a promise, it’s in a pending state. When we call the <code>resolve</code> function, it goes in a fulfilled state and if we call <code>reject</code> it will go in the rejected state.</p>
<p>To simulate the long-running or asynchronous operation, we will use the <code>setTimeout</code> function.</p>
<pre><code class="lang-js"><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-keyword">function</span>(<span class="hljs-params">resolve, reject</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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span>;
  resolve(sum);
 }, <span class="hljs-number">2000</span>);
});
</code></pre>
<p>Here, we've created a promise which will resolve to the sum of <code>4</code> and <code>5</code> after a 2000ms (2 second) timeout is over.</p>
<p>To get the result of the successful promise execution, we need to register a callback using <code>.then</code> like this:</p>
<pre><code class="lang-js"><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-keyword">function</span>(<span class="hljs-params">resolve, reject</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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span>;
  resolve(sum);
 }, <span class="hljs-number">2000</span>);
});

promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// 9</span>
});
</code></pre>
<p>So whenever we call <code>resolve</code>, the promise will return back the value passed to the <code>resolve</code> function which we can collect using the <code>.then</code> handler.</p>
<p>If the operation is not successful, then we call the <code>reject</code> function like this:</p>
<pre><code class="lang-js"><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-keyword">function</span>(<span class="hljs-params">resolve, reject</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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span> + <span class="hljs-string">'a'</span>;
  <span class="hljs-keyword">if</span>(<span class="hljs-built_in">isNaN</span>(sum)) {
    reject(<span class="hljs-string">'Error while calculating sum.'</span>);
  } <span class="hljs-keyword">else</span> {
    resolve(sum);
  }
 }, <span class="hljs-number">2000</span>);
});

promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(result);
});
</code></pre>
<p>Here, if the <code>sum</code> is not a number, then we call the <code>reject</code> function with the error message. Otherwise we call the <code>resolve</code> function.</p>
<p>If you execute the above code, you will see the following output:</p>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/9adf1d42d876e2b87ef0ecfbf97b06a01c026eba/error_no_catch.png" alt="Error without catch" width="600" height="400" loading="lazy"></p>
<p>As you can see, we're getting an uncaught error message along with the message we've specified because calling <code>reject</code> function throws an error. But we have not added an error handler for catching that error.</p>
<p>To catch the error, we need to register another callback using <code>.catch</code> like this:</p>
<pre><code class="lang-js">promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(result);
}).catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
 <span class="hljs-built_in">console</span>.log(error);
});
</code></pre>
<p>You will see the following output:</p>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/9adf1d42d876e2b87ef0ecfbf97b06a01c026eba/error_catch.png" alt="Error with catch" width="600" height="400" loading="lazy"></p>
<p>As you can see, we have added the <code>.catch</code> handler, so we're not getting any uncaught error but we're just logging the error to the console.</p>
<p>This also avoids stopping your application abruptly.</p>
<p>So it's always recommended to add the <code>.catch</code> handler to every promise so your application will not stop from running because of the error.</p>
<h3 id="heading-promise-chaining">Promise chaining</h3>
<p>We can add multiple <code>.then</code> handlers to a single promise like this:</p>
<pre><code class="lang-js">promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'first .then handler'</span>);
 <span class="hljs-keyword">return</span> result;
}).then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'second .then handler'</span>);
 <span class="hljs-built_in">console</span>.log(result);
}).catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
 <span class="hljs-built_in">console</span>.log(error);
});
</code></pre>
<p>When we have multiple <code>.then</code> handlers added, the return value of the previous <code>.then</code> handler is automatically passed to the next <code>.then</code> handler.</p>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/9adf1d42d876e2b87ef0ecfbf97b06a01c026eba/promise_chaining.png" alt="Promise Chaining" width="600" height="400" loading="lazy"></p>
<p>As you can see, adding <code>4 + 5</code> resolves a promise and we get that sum in the first <code>.then</code> handler. There we're printing a log statement and returning that sum to the next <code>.then</code> handler.</p>
<p>And inside the next <code>.then</code> handler, we're adding a log statement and then we're printing the result we got from the previous <code>.then</code> handler.</p>
<p>This way of adding multiple <code>.then</code> handlers is known as promise chaining.</p>
<h3 id="heading-how-to-delay-a-promises-execution-in-javascript">How to delay a promise's execution in JavaScript</h3>
<p>Many times we don't want to create promise immediately but want to create one after some operation is completed.</p>
<p>To achieve this, we can wrap the promise in a function and return that promise from that function like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPromise</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-keyword">function</span>(<span class="hljs-params">resolve, reject</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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span>;
   <span class="hljs-keyword">if</span>(<span class="hljs-built_in">isNaN</span>(sum)) {
     reject(<span class="hljs-string">'Error while calculating sum.'</span>);
   } <span class="hljs-keyword">else</span> {
    resolve(sum);
   }
  }, <span class="hljs-number">2000</span>);
 });
}
</code></pre>
<p>This way, we can use the function parameters inside the promise, making the function truly dynamic.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPromise</span>(<span class="hljs-params">a, b</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-keyword">function</span>(<span class="hljs-params">resolve, reject</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-keyword">const</span> sum = a + b;
   <span class="hljs-keyword">if</span>(<span class="hljs-built_in">isNaN</span>(sum)) {
     reject(<span class="hljs-string">'Error while calculating sum.'</span>);
   } <span class="hljs-keyword">else</span> {
    resolve(sum);
   }
  }, <span class="hljs-number">2000</span>);
 });
}

createPromise(<span class="hljs-number">1</span>,<span class="hljs-number">8</span>)
 .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">output</span>) </span>{
  <span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">// 9</span>
});

<span class="hljs-comment">// OR</span>

createPromise(<span class="hljs-number">10</span>,<span class="hljs-number">24</span>)
 .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">output</span>) </span>{
  <span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">// 34</span>
});
</code></pre>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/9adf1d42d876e2b87ef0ecfbf97b06a01c026eba/general_function.png" alt="Output" width="600" height="400" loading="lazy"></p>
<p><strong>Note:</strong> When we create a promise, it will be either resolved or rejected but not both at the same time. So we cannot add two <code>resolve</code> or <code>reject</code> function calls in the same promise.</p>
<p>Also, we can pass only a single value to the <code>resolve</code> or <code>reject</code> function.</p>
<p>If you want to pass multiple values to a <code>resolve</code> function, pass it as an object like this:</p>
<pre><code class="lang-js"><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-keyword">function</span>(<span class="hljs-params">resolve, reject</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-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span>;
  resolve({
   <span class="hljs-attr">a</span>: <span class="hljs-number">4</span>,
   <span class="hljs-attr">b</span>: <span class="hljs-number">5</span>,
   sum
  });
 }, <span class="hljs-number">2000</span>);
});

promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
 <span class="hljs-built_in">console</span>.log(result);
}).catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
 <span class="hljs-built_in">console</span>.log(error);
});
</code></pre>
<p><img src="https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/65fba14b45b22228f49107634d440903eb0c8dbd/object_resolve.png" alt="Resolving object" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-use-arrow-functions-in-javascript">How to use arrow functions in JavaScript</h3>
<p>In all the above code examples, we've used regular ES5 function syntax while creating promises. But it's a common practice to use arrow function syntax instead of ES5 function syntax like this:</p>
<pre><code class="lang-js"><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-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> sum = <span class="hljs-number">4</span> + <span class="hljs-number">5</span> + <span class="hljs-string">'a'</span>;
  <span class="hljs-keyword">if</span>(<span class="hljs-built_in">isNaN</span>(sum)) {
    reject(<span class="hljs-string">'Error while calculating sum.'</span>);
  } <span class="hljs-keyword">else</span> {
    resolve(sum);
  }
 }, <span class="hljs-number">2000</span>);
});

promise.then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
 <span class="hljs-built_in">console</span>.log(result);
});
</code></pre>
<p>You can either use ES5 or ES6 function syntax depending on your preferences and needs.</p>
<h2 id="heading-es6-import-and-export-syntax">ES6 Import And Export Syntax</h2>
<p>Before ES6 came into play, we used multiple <code>script</code> tags in a single HTML file to import different JavaScript files like this:</p>
<pre><code class="lang-js">&lt;script type=<span class="hljs-string">"text/javascript"</span> src=<span class="hljs-string">"home.js"</span>&gt;&lt;/script&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"profile.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"user.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>So, if we had a variable with the same name in different JavaScript files, it would create a naming conflict and the value you were expecting would not be the actual value you got.</p>
<p>ES6 has fixed this issue with the concept of modules.</p>
<p>Every JavaScript file we write in ES6 is known as a module. The variables and functions we declare in each file are not available to other files until we specifically export them from that file and import them into another file.</p>
<p>So the functions and variables defined in the file are private to each file and can’t be accessed outside the file until we export them.</p>
<p>There are two types of exports:</p>
<ul>
<li>Named Exports: There can be multiple named exports in a single file</li>
<li>Default Exports: There can be only one default export in a single file</li>
</ul>
<h3 id="heading-named-exports-in-javascript">Named Exports in JavaScript</h3>
<p>To export a single value as a named export, we export it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> temp = <span class="hljs-string">"This is some dummy text"</span>;
</code></pre>
<p>If we have multiple things to export, we can write an export statement on a separate line instead of in front of variable declaration. We specify the things to export in curly brackets.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> temp1 = <span class="hljs-string">"This is some dummy text1"</span>;
<span class="hljs-keyword">const</span> temp2 = <span class="hljs-string">"This is some dummy text2"</span>;

<span class="hljs-keyword">export</span> { temp1, temp2 };
</code></pre>
<p>Note that the export syntax is not an object literal syntax. So in ES6, to export something we can't use key-value pairs like this:</p>
<pre><code class="lang-js"> <span class="hljs-comment">// This is invalid syntax of export in ES6</span>

<span class="hljs-keyword">export</span> { <span class="hljs-attr">key1</span>: value1, <span class="hljs-attr">key2</span>: value2 }
</code></pre>
<p>To import the things we exported as a named export, we use the following syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { temp1, temp2 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./filename'</span>;
</code></pre>
<p>Note that while importing something from the file, we don't need to add the <code>.js</code> extension to the filename as it's considered by default.</p>
<pre><code class="lang-js"><span class="hljs-comment">// import from functions.js file from current directory </span>
<span class="hljs-keyword">import</span> { temp1, temp2 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./functions'</span>;

<span class="hljs-comment">// import from functions.js file from parent of current directory</span>
<span class="hljs-keyword">import</span> { temp1 } <span class="hljs-keyword">from</span> <span class="hljs-string">'../functions'</span>;
</code></pre>
<p>Here's a Code Sandbox demo: <a target="_blank" href="https://codesandbox.io/s/hardcore-pond-q4cjx">https://codesandbox.io/s/hardcore-pond-q4cjx</a></p>
<p><strong>One thing to note is that the name used while exporting has to match the name we use while importing.</strong></p>
<p>So if you are exporting as:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14159</span>;
</code></pre>
<p>then while importing you have to use the same name used while exporting:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { PI } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>You can't use any other name like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { PiValue } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>; <span class="hljs-comment">// This will throw an error</span>
</code></pre>
<p>But if you already have the variable with the same name as the exported variable, you can use the renaming syntax while importing like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { PI <span class="hljs-keyword">as</span> PIValue } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>Here we have renamed <code>PI</code> to <code>PIValue</code> and so we can’t use the <code>PI</code> variable name now. Instead, we have to use the <code>PIValue</code> variable to get the exported value of <code>PI</code>.</p>
<p>We can also use the renaming syntax at the time of exporting:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14159</span>; 

<span class="hljs-keyword">export</span> { PI <span class="hljs-keyword">as</span> PIValue };
</code></pre>
<p>then while importing we have to use <code>PIValue</code> like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { PIValue } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>To export something as a named export, we have to declare it first.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-string">'hello'</span>; <span class="hljs-comment">// this will result in error</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> greeting = <span class="hljs-string">'hello'</span>; <span class="hljs-comment">// this will work</span>
<span class="hljs-keyword">export</span> { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span> }; <span class="hljs-comment">// This will result in error</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> object = { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span> }; <span class="hljs-comment">// This will work</span>
</code></pre>
<p><strong>The order in which we import the multiple named exports is not important.</strong></p>
<p>Take a look at the below <code>validations.js</code> file:</p>
<pre><code class="lang-js"><span class="hljs-comment">// utils/validations.js</span>

<span class="hljs-keyword">const</span> isValidEmail = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">email</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/^[^@ ]+@[^@ ]+\.[^@ \.]{2,}$/</span>.test(email)) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"email is valid"</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"email is invalid"</span>;
  }
};

<span class="hljs-keyword">const</span> isValidPhone = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">phone</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/^[\\(]\d{3}[\\)]\s\d{3}-\d{4}$/</span>.test(phone)) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"phone number is valid"</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"phone number is invalid"</span>;
  }
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isEmpty</span>(<span class="hljs-params">value</span>) </span>{ 
  <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/^\s*$/</span>.test(value)) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"string is empty or contains only spaces"</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"string is not empty and does not contain spaces"</span>;
  } 
}

<span class="hljs-keyword">export</span> { isValidEmail, isValidPhone, isEmpty };
</code></pre>
<p>and in <code>index.js</code> we use these functions as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>
<span class="hljs-keyword">import</span> { isEmpty, isValidEmail } <span class="hljs-keyword">from</span> <span class="hljs-string">"./utils/validations"</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"isEmpty:"</span>, isEmpty(<span class="hljs-string">"abcd"</span>)); <span class="hljs-comment">// isEmpty: string is not empty and does not contain spaces</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"isValidEmail:"</span>, isValidEmail(<span class="hljs-string">"abc@11gmail.com"</span>)); <span class="hljs-comment">// isValidEmail: email is valid</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"isValidEmail:"</span>, isValidEmail(<span class="hljs-string">"ab@c@11gmail.com"</span>)); <span class="hljs-comment">// isValidEmail: email is invalid</span>
</code></pre>
<p>Here's a Code Sandbox demo: <a target="_blank" href="https://codesandbox.io/s/youthful-flower-xesus">https://codesandbox.io/s/youthful-flower-xesus</a></p>
<p>As you can see, we can import only the required exported things and in any order, so we don’t need to check in what order we exported in another file. That’s the beauty of named exports.</p>
<h3 id="heading-default-exports-in-javascript">Default Exports in JavaScript</h3>
<p>As I said earlier, there can be at most one default export in a single file.</p>
<p>You can, however, combine multiple named exports and one default export in a single file.</p>
<p>To declare a default export we add the default keyword in front of the export keyword like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">//constants.js</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-string">'David'</span>; 
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> name;
</code></pre>
<p>To import the default export we don’t add the curly brackets as we did in named export like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> name <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>If we have multiple named exports and one default export like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14159</span>; 
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>;

<span class="hljs-keyword">const</span> NAME = <span class="hljs-string">"David"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> NAME;
</code></pre>
<p>then to import everything on a single line we need to use the default exported variable before the curly bracket only.</p>
<pre><code class="lang-js"><span class="hljs-comment">// NAME is default export and PI and AGE are named exports here</span>

<span class="hljs-keyword">import</span> NAME, { PI, AGE } <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p><strong>One specialty of default export is that we can change the name of the exported variable while importing:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AGE;
</code></pre>
<p>And in another file, we can use another name while importing</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> myAge <span class="hljs-keyword">from</span> ‘./constants’; 

<span class="hljs-built_in">console</span>.log(myAge); <span class="hljs-comment">// 30</span>
</code></pre>
<p>Here, we have changed the name of the default exported variable from <code>AGE</code> to <code>myAge</code>.</p>
<p>This works because there can be only one default export so you can name it whatever you want.</p>
<p>Another thing to note about default export is that the export default keyword cannot come before variable declaration like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>; <span class="hljs-comment">// This is an error and will not work</span>
</code></pre>
<p>so we have to use the export default keyword on a separate line like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js </span>

<span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>; 
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AGE;
</code></pre>
<p>We can, however, export default without declaring the variable like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">//constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
 <span class="hljs-attr">name</span>: <span class="hljs-string">"Billy"</span>,
 <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>
};
</code></pre>
<p>and in another file use it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> user <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
<span class="hljs-built_in">console</span>.log(user.name); <span class="hljs-comment">// Billy </span>
<span class="hljs-built_in">console</span>.log(user.age); <span class="hljs-comment">// 40</span>
</code></pre>
<p>There is another way of importing all the variables exported in a file using the following syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> constants <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;
</code></pre>
<p>Here, we are importing all the named and default exports we have in <code>constants.js</code> and stored in the <code>constants</code> variable. So, <code>constants</code> will become an object now.</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> USERNAME = <span class="hljs-string">"David"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
 <span class="hljs-attr">name</span>: <span class="hljs-string">"Billy"</span>,
 <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>
};
</code></pre>
<p>And in another file, we use it as below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// test.js</span>

<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> constants <span class="hljs-keyword">from</span> <span class="hljs-string">'./constants'</span>;

<span class="hljs-built_in">console</span>.log(constants.USERNAME); <span class="hljs-comment">// David</span>
<span class="hljs-built_in">console</span>.log(constants.default); <span class="hljs-comment">// { name: "Billy", age: 40 }</span>
<span class="hljs-built_in">console</span>.log(constants.default.age); <span class="hljs-comment">// 40</span>
</code></pre>
<p>Here's a Code Sandbox demo: <a target="_blank" href="https://codesandbox.io/s/green-hill-dj43b">https://codesandbox.io/s/green-hill-dj43b</a></p>
<p>If you don’t want to export on separate lines for default and named<br>exports, you can combine it as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// constants.js</span>
<span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14159</span>; <span class="hljs-keyword">const</span> AGE = <span class="hljs-number">30</span>;
<span class="hljs-keyword">const</span> USERNAME = <span class="hljs-string">"David"</span>;
<span class="hljs-keyword">const</span> USER = {
 <span class="hljs-attr">name</span>: <span class="hljs-string">"Billy"</span>,
 <span class="hljs-attr">age</span>: <span class="hljs-number">40</span> 
};

<span class="hljs-keyword">export</span> { PI, AGE, USERNAME, USER <span class="hljs-keyword">as</span> <span class="hljs-keyword">default</span> };
</code></pre>
<p>Here, we are exporting <code>USER</code> as the default export and others as named exports.</p>
<p>In another file, you can use it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> USER, { PI, AGE, USERNAME } <span class="hljs-keyword">from</span> <span class="hljs-string">"./constants"</span>;
</code></pre>
<p>Here's a Code Sandbox demo: <a target="_blank" href="https://codesandbox.io/s/eloquent-northcutt-7btp1">https://codesandbox.io/s/eloquent-northcutt-7btp1</a></p>
<h3 id="heading-in-summary">In summary:</h3>
<ol>
<li>In ES6, data declared in one file is not accessible to another file until it is exported from that file and imported into another file.</li>
<li>If we have a single thing in a file to export like class declaration, we use default export otherwise we use named export. We can also combine default and named exports in a single file.</li>
</ol>
<h2 id="heading-default-parameters-in-javascript">Default Parameters in JavaScript</h2>
<p>ES6 has added a pretty useful feature of providing default parameters while defining functions.</p>
<p>Suppose we have an application, where once the user login into the system, we show them a welcome message like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMessage</span>(<span class="hljs-params">firstName</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Welcome back, "</span> + firstName;
}
<span class="hljs-built_in">console</span>.log(showMessage(<span class="hljs-string">'John'</span>)); <span class="hljs-comment">// Welcome back, John</span>
</code></pre>
<p>But what if we don’t have the user name in our database as it was an optional field while registering? Then we can show the <code>Welcome Guest</code> message to the user after login.</p>
<p>So we first need to check if the <code>firstName</code> is provided and then display the corresponding message. Before ES6, we would have had to write code like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMessage</span>(<span class="hljs-params">firstName</span>) </span>{
  <span class="hljs-keyword">if</span>(firstName) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Welcome back, "</span> + firstName;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Welcome back, Guest"</span>;
  }
}

<span class="hljs-built_in">console</span>.log(showMessage(<span class="hljs-string">'John'</span>)); <span class="hljs-comment">// Welcome back, John </span>
<span class="hljs-built_in">console</span>.log(showMessage()); <span class="hljs-comment">// Welcome back, Guest</span>
</code></pre>
<p>But now in ES6 using default function parameters we can write the above code as shown below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMessage</span>(<span class="hljs-params">firstName = <span class="hljs-string">'Guest'</span></span>) </span>{
   <span class="hljs-keyword">return</span> <span class="hljs-string">"Welcome back, "</span> + firstName;
}

<span class="hljs-built_in">console</span>.log(showMessage(<span class="hljs-string">'John'</span>)); <span class="hljs-comment">// Welcome back, John </span>
<span class="hljs-built_in">console</span>.log(showMessage()); <span class="hljs-comment">// Welcome back, Guest</span>
</code></pre>
<p><strong>We can assign any value as a default value to the function parameter.</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">display</span>(<span class="hljs-params">a = <span class="hljs-number">10</span>, b = <span class="hljs-number">20</span>, c = b</span>) </span>{ 
 <span class="hljs-built_in">console</span>.log(a, b, c);
}

display(); <span class="hljs-comment">// 10 20 20</span>
display(<span class="hljs-number">40</span>); <span class="hljs-comment">// 40 20 20</span>
display(<span class="hljs-number">1</span>, <span class="hljs-number">70</span>); <span class="hljs-comment">// 1 70 70</span>
display(<span class="hljs-number">1</span>, <span class="hljs-number">30</span>, <span class="hljs-number">70</span>); <span class="hljs-comment">// 1 30 70</span>
</code></pre>
<p>As you can see, we have assigned unique values to a and b function parameters but for c we're assigning the value of b. So whatever value we have provided for b will be assigned to c also if there is no specific value provided for c while calling the function.</p>
<p>In the above code, we have not provided all the arguments to the function. So the above function calls will be the same as below:</p>
<pre><code class="lang-js">display(); <span class="hljs-comment">// is same as display(undefined, undefined, undefined)</span>
display(<span class="hljs-number">40</span>); <span class="hljs-comment">// is same as display(40, undefined, undefined)</span>
display(<span class="hljs-number">1</span>, <span class="hljs-number">70</span>); <span class="hljs-comment">// is same as display(1, 70, undefined)</span>
</code></pre>
<p>So if the argument passed is <code>undefined</code>, the default value will be used for the corresponding parameter.</p>
<p><strong>We can also assign complex or calculated values as a default value.</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> defaultUser = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>,
  <span class="hljs-attr">location</span>: <span class="hljs-string">'NY'</span>,
  <span class="hljs-attr">job</span>: <span class="hljs-string">'Software Developer'</span>
};

<span class="hljs-keyword">const</span> display = <span class="hljs-function">(<span class="hljs-params">user = defaultUser, age = <span class="hljs-number">60</span> / <span class="hljs-number">2</span> </span>) =&gt;</span> { 
 <span class="hljs-built_in">console</span>.log(user, age);
};
display();

<span class="hljs-comment">/* output

{
  name: 'Jane',
  location: 'NY',
  job: 'Software Developer'
} 30 

*/</span>
</code></pre>
<p>Now, take a look at the below ES5 code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params">page, results, gender, nationality</span>) </span>{
  <span class="hljs-keyword">var</span> params = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">if</span>(page === <span class="hljs-number">0</span> || page) {
   params += <span class="hljs-string">`page=<span class="hljs-subst">${page}</span>&amp;`</span>; 
  }
  <span class="hljs-keyword">if</span>(results) {
   params += <span class="hljs-string">`results=<span class="hljs-subst">${results}</span>&amp;`</span>;
  }
  <span class="hljs-keyword">if</span>(gender) {
   params += <span class="hljs-string">`gender=<span class="hljs-subst">${gender}</span>&amp;`</span>;
  }
  <span class="hljs-keyword">if</span>(nationality) {
   params += <span class="hljs-string">`nationality=<span class="hljs-subst">${nationality}</span>`</span>;
  }

  fetch(<span class="hljs-string">'https://randomuser.me/api/?'</span> + params) 
   .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">response</span>) </span>{
     <span class="hljs-keyword">return</span> response.json(); 
   })
   .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{ 
    <span class="hljs-built_in">console</span>.log(result);
   }) 
   .catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'error'</span>, error); 
   }); 
}

getUsers(<span class="hljs-number">0</span>, <span class="hljs-number">10</span>, <span class="hljs-string">'male'</span>, <span class="hljs-string">'us'</span>);
</code></pre>
<p>In this code, we’re making an API call to the <a target="_blank" href="https://randomuser.me/">Random user</a> API by passing various optional parameters in the <code>getUsers</code> function.</p>
<p>So before making the API call, we have added various if conditions to check if the parameter is added or not, and based on that we’re constructing the query string like this: <code>https://randomuser.me/api/? page=0&amp;results=10&amp;gender=male&amp;nationality=us</code>.</p>
<p>But instead of adding so many if conditions, we can use the default parameters while defining the function parameters as shown below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params">page = <span class="hljs-number">0</span>, results = <span class="hljs-number">10</span>, gender = <span class="hljs-string">'male'</span>,nationality = <span class="hljs-string">'us'</span></span>) </span>{
 fetch(<span class="hljs-string">`https://randomuser.me/api/?page=<span class="hljs-subst">${page}</span>&amp;results=<span class="hljs-subst">${results}</span>&amp;gender=<span class="hljs-subst">${gender}</span>&amp;nationality=<span class="hljs-subst">${nationality}</span>`</span>)
 .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">response</span>) </span>{ 
  <span class="hljs-keyword">return</span> response.json();
 }) 
 .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
   <span class="hljs-built_in">console</span>.log(result); 
 })
 .catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{ 
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'error'</span>, error);
  }); 
}

getUsers();
</code></pre>
<p>As you can see, we have simplified the code a lot. So when we don’t provide any argument to the <code>getUsers</code> function, it will take default values and we can also provide our own values like this:</p>
<pre><code class="lang-js">getUsers(<span class="hljs-number">1</span>, <span class="hljs-number">20</span>, <span class="hljs-string">'female'</span>, <span class="hljs-string">'gb'</span>);
</code></pre>
<p>So it will override the default parameters of the function.</p>
<h3 id="heading-null-is-not-equal-to-undefined">null is not equal to undefined</h3>
<p>But you need to be aware of one thing: <code>null</code> and <code>undefined</code> are two different things while defining default parameters.</p>
<p>Take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">display</span>(<span class="hljs-params">name = <span class="hljs-string">'David'</span>, age = <span class="hljs-number">35</span>, location = <span class="hljs-string">'NY'</span></span>)</span>{
 <span class="hljs-built_in">console</span>.log(name, age, location); 
}

display(<span class="hljs-string">'David'</span>, <span class="hljs-number">35</span>); <span class="hljs-comment">// David 35 NY</span>
display(<span class="hljs-string">'David'</span>, <span class="hljs-number">35</span>, <span class="hljs-literal">undefined</span>); <span class="hljs-comment">// David 35 NY</span>
</code></pre>
<p>As we have not provided the third value for the location parameter in the first call to display, it will be <code>undefined</code> by default so the default value of location will be used in both of the function calls. But the below function calls are not equal.</p>
<pre><code class="lang-js">display(<span class="hljs-string">'David'</span>, <span class="hljs-number">35</span>, <span class="hljs-literal">undefined</span>); <span class="hljs-comment">// David 35 NY</span>
display(<span class="hljs-string">'David'</span>, <span class="hljs-number">35</span>, <span class="hljs-literal">null</span>); <span class="hljs-comment">// David 35 null</span>
</code></pre>
<p>When we pass <code>null</code> as an argument, we’re specifically saying to assign a <code>null</code> value to the <code>location</code> parameter which is not the same as <code>undefined</code>. So it will not take the default value of <code>NY</code>.</p>
<h2 id="heading-arrayprototypeincludes">Array.prototype.includes</h2>
<p>ES7 has added a new function that checks if an element is present in the array or not and returns a boolean value of either <code>true</code> or <code>false</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 Code</span>

<span class="hljs-keyword">const</span> numbers = [<span class="hljs-string">"one"</span>, <span class="hljs-string">"two"</span>, <span class="hljs-string">"three"</span>, <span class="hljs-string">"four"</span>];

<span class="hljs-built_in">console</span>.log(numbers.indexOf(<span class="hljs-string">"one"</span>) &gt; <span class="hljs-number">-1</span>); <span class="hljs-comment">// true </span>
<span class="hljs-built_in">console</span>.log(numbers.indexOf(<span class="hljs-string">"five"</span>) &gt; <span class="hljs-number">-1</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p>The same code using the Array <code>includes</code> method can be written as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES7 Code</span>

<span class="hljs-keyword">const</span> numbers = [<span class="hljs-string">"one"</span>, <span class="hljs-string">"two"</span>, <span class="hljs-string">"three"</span>, <span class="hljs-string">"four"</span>];

<span class="hljs-built_in">console</span>.log(numbers.includes(<span class="hljs-string">"one"</span>)); <span class="hljs-comment">// true </span>
<span class="hljs-built_in">console</span>.log(numbers.includes(<span class="hljs-string">"five"</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>So using the Array <code>includes</code> methods makes code short and easy to understand.</p>
<p>The <code>includes</code> method also comes in handy when comparing with different values.</p>
<p>Take a look at the below code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> day = <span class="hljs-string">"monday"</span>;

<span class="hljs-keyword">if</span>(day === <span class="hljs-string">"monday"</span> || day === <span class="hljs-string">"tuesday"</span> || day === <span class="hljs-string">"wednesday"</span>) {
  <span class="hljs-comment">// do something</span>
}
</code></pre>
<p>The above code using the <code>includes</code> method can be simplified as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> day = <span class="hljs-string">"monday"</span>;

<span class="hljs-keyword">if</span>([<span class="hljs-string">"monday"</span>, <span class="hljs-string">"tuesday"</span>, <span class="hljs-string">"wednesday"</span>].includes(day)) {
  <span class="hljs-comment">// do something</span>
}
</code></pre>
<p>So the <code>includes</code> method is pretty handy when checking for values in an array.</p>
<h2 id="heading-closing-points">Closing points</h2>
<p>There are many changes that have been incorporated into JavaScript starting from ES6. And every JavaScript, Angular, React, or Vue developer should be aware of them.</p>
<p>Knowing them makes you a better developer and can even help you get a higher paying job. And if you're just learning libraries like React and frameworks like Angular and Vue, you'll certainly want to be familiar with these new features.</p>
<h2 id="heading-learn-more-about-modern-javascript-features">Learn more about Modern JavaScript features</h2>
<p>You can learn everything about the latest features added in JavaScript in my <a target="_blank" href="https://modernjavascript.yogeshchavan.dev/">Mastering Modern JavaScript</a> book. It is the only guide you need to learn modern JavaScript concepts.</p>
<p><a target="_blank" href="https://modernjavascript.yogeshchavan.dev/"><img src="https://modernjavascript.yogeshchavan.dev/book_cover.jpg" width="512" height="800" alt="book_cover" loading="lazy"></a></p>
<p>Subscribe to my <a target="_blank" href="https://bit.ly/2HwVEA2">weekly newsletter</a> to join 1000+ other subscribers to get amazing tips, tricks, and articles directly in your inbox.</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>
        
    </channel>
</rss>
