<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ asynchronous - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ asynchronous - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 22 May 2026 17:39:54 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/asynchronous/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How the Node.js Event Loop Works ]]>
                </title>
                <description>
                    <![CDATA[ The Node.js event loop is a concept that may seem difficult to understand at first. But as with any seemingly complex subject, the best way to understand it is often through an analogy. In this article, you’ll learn how overworked managers, busy wait... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-the-nodejs-event-loop-works/</link>
                <guid isPermaLink="false">68b86cca911797ceb3fd37e0</guid>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Event Loop ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ synchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ parallelism ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Amanda Ene Adoyi ]]>
                </dc:creator>
                <pubDate>Wed, 03 Sep 2025 16:28:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756916907320/01074df6-0f8e-4a63-9a3e-07c8297fc22b.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Node.js event loop is a concept that may seem difficult to understand at first. But as with any seemingly complex subject, the best way to understand it is often through an analogy.</p>
<p>In this article, you’ll learn how overworked managers, busy waiters, and train stations can help bring home the fundamental concept of the event loop. If you’re working with Node, you’ll need to understand how the event loop works, as it lies at the root of some of the most powerful applications today.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-synchronous-and-asynchronous-code">What are Synchronous and Asynchronous Code?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-concurrency-and-parallelism-mean">What Concurrency and Parallelism Mean</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-concurrency-in-nodejs">Concurrency in Node.js</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-parallelism-in-nodejs">Parallelism in Node.js</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-event-loop">What is the Event Loop?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-phases-of-the-event-loop">The Phases of the Event Loop</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>In order to seamlessly follow along with this article, it would help if you are familiar with the following concepts:</p>
<ol>
<li><p><strong>A basic understanding of JavaScript:</strong> Node.js runs on JavaScript, so you’ll need to understand variables, functions, and control flow.</p>
</li>
<li><p><strong>Familiarity with Node.js basics:</strong> Running simple scripts with Node and requiring modules.</p>
</li>
<li><p><strong>Some exposure to asynchronous patterns:</strong> Knowing what patterns such as <code>setTimeout()</code> do.</p>
</li>
<li><p><strong>Some familiarity with basic CPU concepts (cores and threads):</strong> This will help you better understand concurrency and parallelism.</p>
</li>
<li><p><strong>Awareness of promises and async/await:</strong> This is optional and not a strict requirement, but will be helpful.</p>
</li>
</ol>
<h2 id="heading-what-are-synchronous-and-asynchronous-code">What are Synchronous and Asynchronous Code?</h2>
<p>When writing code for Node.js applications, there are two different ways it can run: synchronous (sync) and asynchronous (async). Synchronous code is referred to as <em>blocking</em> because when it runs, no other code runs until execution is complete.</p>
<p>An analogy for this is a busy restaurant. Picture a waiter who refuses to wait on other tables until the table they’re presently serving has received their orders and has started eating. While the food is being prepared, the waiter waits around doing nothing and only approaches your table to take your order when they are completely finished with the previous table. Needless to say, the waiter may not receive a great tip for that service.</p>
<p>This is what synchronous code is. It halts the execution of other processes until it’s complete. You can see how it works in the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> syncWaiter = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${name}</span> attends to tables pretty slowly.`</span>);
};

syncWaiter(<span class="hljs-string">"Devin"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"At least all the orders are correct!"</span>);
</code></pre>
<p>The code above will be run in sequence, in the order it appears.</p>
<p>Asynchronous code, unlike synchronous code, doesn’t halt all other processes until one task is executed – rather, it proceeds to carry out other tasks while a longer process runs in the background.</p>
<p>Using our waiter analogy, in this case the waiter in the restaurant would go take an order from one table, pass the order to the kitchen, and while it’s being prepared, proceeds to your table to take your order as well. This way, the waiter is able to ensure different processes are started even if one process takes a bit longer than the rest. Check out the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> asyncWaiter = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span> {<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${name}</span> attends to tables pretty quickly.`</span>)}, <span class="hljs-number">3000</span>)
};

asyncWaiter(<span class="hljs-string">"James"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Wow! All the tables are attended to in a short time."</span>);
</code></pre>
<p>Unlike synchronous code, this code does run the function <code>asyncWaiter()</code> – but the callback inside the function executes later. When the duration elapses, the result is then shown on the screen. This is why asynchronous programs are referred to as <em>non-blocking.</em> They don’t halt the program, but move from one available task to another.</p>
<p>The code above returns the following:</p>
<pre><code class="lang-bash">Wow! All the tables are attended to <span class="hljs-keyword">in</span> a short time.
James attends to tables pretty quickly.
</code></pre>
<p>This print order happens because of how the <em>event loop</em> manages tasks: the synchronous <code>console.log()</code> that comes after <code>asyncWaiter()</code> runs immediately, while the asynchronous callback inside <code>asyncWaiter()</code> (from <code>setTimeout</code>) is scheduled to run later. If you don’t understand this just yet, don’t worry as I’ll break it down in detail shortly.</p>
<h2 id="heading-what-concurrency-and-parallelism-mean">What Concurrency and Parallelism Mean</h2>
<p>Node.js is single-threaded but often gives the appearance of a multi-threaded environment due to how it handles concurrency and parallelism. A thread is a single sequence of instructions executed by the CPU independently. Think of it like a single waiter named James in a restaurant.</p>
<p>If James handles multiple tasks around the same time and quickly, an onlooker outside the restaurant who sees the number of customers moving in and out of the restaurant may assume that there are a ton of waiters serving tables. In reality, James just handles his tasks asynchronously.</p>
<p>Before grasping the concept of the event loop, it’s good to understand what concurrency and parallelism are, as they help explain this.</p>
<h3 id="heading-concurrency-in-nodejs">Concurrency in Node.js</h3>
<p>Concurrency means having multiple processes run around the same time. In the waiter analogy, it is like James carrying out different tasks, though not simultaneously. He could, for instance take an order from a table and, while waiting for the food to arrive, request that extra salt be provided to another table. While the salt is on its way, he uses the waiting time to read the bill to a third table.</p>
<p>The key idea is that James never sits idle — he works on other tasks while waiting for one to finish. If this sounds an awful lot like asynchronous programming, it is because asynchronous code is just one way to achieve concurrency.</p>
<p>Other ways to execute concurrency are <a target="_blank" href="https://www.freecodecamp.org/news/multithreading-for-beginners/">multithreading</a> on a single CPU core and <a target="_blank" href="https://www.freecodecamp.org/news/how-to-handle-concurrency-in-go/">coroutines</a> which are just functions that pause their execution to resume at a later time.</p>
<h3 id="heading-parallelism-in-nodejs">Parallelism in Node.js</h3>
<p>Parallelism, on the other hand, also means having several tasks run at the same time – but instead of the tasks just being processed around the same time, they are executed at exactly the same time, simultaneously. In this case, the restaurant manager decides to hire multiple waiters and each table has a waiter who is taking orders at exactly the same time.</p>
<p>Parallelism can be achieved using multithreading on multiple CPU cores. In this setup, the threads share the same memory and run simultaneously while using clusters which run independently – each with its own memory space. Here’s a clear example of parallelism using the <code>worker_threads</code> module:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { Worker}  = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);

<span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'./worker.js'</span>);
<span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'./worker.js'</span>);
<span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'./worker.js'</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Main thread keeps running in the process..."</span>);
</code></pre>
<p>The code above creates three worker threads in parallel on a multi-core machine. This doesn’t stop the main thread which continues to run, allowing each worker thread independently do its task. <code>worker.js</code> could be a simple file carrying out any task. In this case, it simply logs a message to the screen:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This worker thread is running here!"</span>);
</code></pre>
<p>Note that the argument for the <code>Worker</code> constructor can be any file path, and the order in which they are executed isn’t dependent on the order they appear in code. Each worker runs independently of the others and they run in parallel.</p>
<p>Concurrency and parallelism allow Node.js (which is single-threaded) to appear to manage multiple tasks simultaneously. Understanding these concepts sets the stage for the event loop, showing how Node.js manages to give the appearance of concurrency while still executing code in a single-threaded environment.</p>
<h2 id="heading-what-is-the-event-loop">What is the Event Loop?</h2>
<p>The event loop listens for events in the Node.js environment. It essentially listens for actions and then processes tasks or outputs values.</p>
<p>To better understand how this works, you can picture the Node.js environment as a fast-paced organization and the event loop as an overworked manager who refuses to hire a personal assistant. The manager oversees the operations of the entire office, and has a dedicated desk that contains whatever they are working on at that particular time. Let’s call this desk <em>the call stack</em>.</p>
<p>The call stack consists of whatever processes or tasks that Node.js is currently working on. When input is entered or code is written to do something, it gets moved to the call stack and from there gets executed.</p>
<p>The order in which this execution takes place is important, as synchronous code makes it to the call stack before asynchronous code. What happens to the asynchronous code you may ask? It goes into something known as the callback queue first before ending up on the call stack.</p>
<p>The callback queue is a lineup of asynchronous tasks that make it to the call stack only if the stack is empty. You can think of it like a file cabinet in the office, where asynchronous code that is processed by a specialized team of workers under the manager go to stay until the manager’s desk is cleared. The manager only heads to the cabinet when they’re done handling all the synchronous task on the call stack. This specialized team that handles asynchronous code like callbacks and async/await are the Node APIs or the Web APIs.</p>
<p>Node or Web APIs process asynchronous code. When the code comes in, it’s processed here and then placed in the callback queue for the event loop to pick up and take to the call stack. But there are some asynchronous tasks that are prioritized. These are known as microtasks, such as <a target="_blank" href="https://www.freecodecamp.org/news/guide-to-javascript-promises/">promises</a>.</p>
<p>Microtasks are given particular priority and are queued in a special microtask queue. This is usually checked after an operation before checking the callback queue. If nothing is present, the event loop checks the callback queue but if some task exists such as <code>process.nextTick()</code>, it gets handled immediately. Macrotasks consist of tasks that are regularly scheduled and handled by the event loop only after the microtasks are treated, such as <code>setTimeout()</code> and <code>setInterval()</code><em>.</em></p>
<p>So as you can see, the event loop is basically what it sounds like – a loop. It looks through events and handles tasks based on a prioritized schedule.</p>
<p>One thing to note, though, is that even within callback queues and microtask queues, there are phases. The event loop, for instance, must handle certain tasks before others even within the same category. This is where the phases of the event loop come in.</p>
<h2 id="heading-the-phases-of-the-event-loop">The Phases of the Event Loop</h2>
<p>By analogy, the event loop is akin to a manager who checks the status of projects and tasks at regular intervals. In this case, they have a specific schedule for checking the status of projects. Some projects or tasks take priority over others, and the manager has to look through them in a set order.</p>
<p>You can also visualize event loop phases as a train moving from station to station. It starts from one location and moves to others in a particular order until it’s complete, then starts the journey again. This arrangement determines what tasks get executed before others.</p>
<p>Here are the phases of the event loop in order:</p>
<ol>
<li><p>The timers phase: This phase executes the <code>setTimeout()</code> and <code>setInterval()</code> callbacks after the duration is run. The event loop starts here, like the first station on a train’s journey.</p>
</li>
<li><p>The pending callbacks phase: These are system-level callbacks, checked after the timers phase operations.</p>
</li>
<li><p>The poll phase: This phase handles input/output (I/O) events and executes the callbacks. In the absence of callbacks, the event loop waits for new ones here.</p>
</li>
<li><p>The check phase: This phase executes <code>setImmediate()</code> callbacks.</p>
</li>
<li><p>Close callbacks: This phase is concerned with executing close events like socket closes.</p>
</li>
</ol>
<p>These callback events are checked in order and run accordingly, so that if <code>setTimeout()</code> and <code>setImmediate()</code> are in the same code, <code>setTimeout()</code> runs first unless the “train” is say, in the Poll Phase of the loop so that <code>setImmediate()</code> runs before <code>setTimeout()</code>.</p>
<p>You can see this illustrated with the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

fs.readFile(<span class="hljs-string">'trainMap.txt'</span>, <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">"Train takes off"</span>);
    }, <span class="hljs-number">0</span>);
    setImmediate(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Oops! Immediate halt! There's a cat on the tracks!"</span>);
    })
});
</code></pre>
<p>You see in the code above that the callbacks are handled asynchronously. Recall that the event loop waits for new callbacks in the poll phase. What this means is that since <code>fs.readfile()</code> is a callback, it gets processed in the poll phase.</p>
<p><code>setTimeout()</code> is set to run in the timers phase but the event loop proceeds to the check phase (which comes next) where <code>setImmediate()</code> is executed. This is why <code>setImmediate()</code> runs before <code>setTimeout()</code> in this case. The event loop then continues from the check phase to the close phase, back to the timers phase, repeating this cycle continuously.</p>
<p>This explains why you see the output below printed to the screen:</p>
<pre><code class="lang-bash">Oops! Immediate halt! There<span class="hljs-string">'s a cat on the tracks!
Train takes off</span>
</code></pre>
<p>This illustrates how the event loop enforces order of execution across the different phases, ensuring that asynchronous operations run in the correct sequence.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The Node.js event loop can sometimes appear mysterious, but it really isn’t as complex as it first seems. At its core, it really is just the engine that ensures JavaScript can handle multiple tasks without freezing.</p>
<p>In this article, you’ve learnt about synchronous and asynchronous code, concurrency, parallelism, and how these concepts help explain the event loop and the phases of the event loop. Understanding how they work gives you the confidence to write asynchronous code without fear, debug more efficiently, and appreciate the power behind Node.js’s ability to handle concurrent tasks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <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[ Learn Async Programming in TypeScript: Promises, Async/Await, and Callbacks [Full Handbook] ]]>
                </title>
                <description>
                    <![CDATA[ Async programming is a programming paradigm that allows you to write code that runs asynchronously. In contrast to synchronous programming, which executes code sequentially, async programming allows code to run in the background while the rest of the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-async-programming-in-typescript-promises-asyncawait-and-callbacks/</link>
                <guid isPermaLink="false">679ced2e80ebdc55d3ee44c8</guid>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Isaiah Clifford Opoku ]]>
                </dc:creator>
                <pubDate>Fri, 31 Jan 2025 15:33:02 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737747600016/f6df015b-cc25-4c37-8c4e-bec9c8c49dc5.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Async programming is a programming paradigm that allows you to write code that runs <code>asynchronously</code>. In contrast to synchronous programming, which executes code sequentially, async programming allows code to run in the background while the rest of the program continues to execute. This is particularly useful for tasks that may take a long time to complete, such as fetching data from a remote API.</p>
<p><code>Async programming</code> is essential for creating responsive and efficient applications in JavaScript. TypeScript, a superset of JavaScript, makes it even easier to work with async programming.</p>
<p>There are several approaches to <code>async programming</code> in TypeScript, including using <code>promises</code>, <code>async/await</code>, and <code>callbacks</code>. We will cover each of these approaches in detail so that you can choose the best one(s) for your use case.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-why-is-async-programming-important">Why is Async Programming Important?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-typescript-makes-async-programming-easier">How TypeScript Makes Async Programming Easier</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-promises-in-typescript">How to Use Promises in TypeScript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-promise">How to Create a Promise</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-chain-promises">How to Chain Promises</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-async-await-in-typescript">How to Use Async / Await in TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-callbacks-in-typescript">How to Use Callbacks in TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-why-is-async-programming-important">Why is Async Programming Important?</h2>
<p>Async programming is crucial for building responsive and efficient web applications. It allows tasks to run in the background while the rest of the program continues, keeping the user interface responsive to input. Also, async programming can boost overall performance by letting multiple tasks run at the same time.</p>
<p>There are many real-world examples of async programming, such as accessing user cameras and microphones and handling user input events. Even if you don't frequently create asynchronous functions, it's important to know how to use them correctly to make sure your application is reliable and performs well.</p>
<h3 id="heading-how-typescript-makes-async-programming-easier">How TypeScript Makes Async Programming Easier</h3>
<p>TypeScript offers several features that simplify async programming, including <code>type safety</code>, <code>type inference</code>, <code>type checking</code>, and <code>type annotations</code>.</p>
<p>With type safety, you can ensure your code behaves as expected, even when dealing with asynchronous functions. For instance, TypeScript can catch errors related to null and undefined values at compile time, saving you time and effort in debugging.</p>
<p>TypeScript's type inference and checking also reduce the amount of boilerplate code you need to write, making your code more concise and easier to read.</p>
<p>And TypeScript's type annotations provide clarity and documentation for your code, which is especially helpful when working with asynchronous functions that can be complex to understand.</p>
<p>Now let’s dive in and learn about these three key features of asynchronous programming: promises, async/await, and callbacks.</p>
<h2 id="heading-how-to-use-promises-in-typescript">How to Use Promises in TypeScript</h2>
<p><strong>Promises</strong> are a powerful tool for handling asynchronous operations in TypeScript. For instance, you might use a promise to fetch data from an external API or to perform a time-consuming task in the background while your main thread keeps running.</p>
<p>To use a Promise, you create a new instance of the <code>Promise</code> class and pass it a function that carries out the asynchronous operation. This function should call the resolve method with the result when the operation succeeds or the reject method with an error if it fails.</p>
<p>Once the Promise is created, you can attach callbacks to it using the <code>then</code> method. These callbacks will be triggered when the Promise is fulfilled, with the resolved value passed as a parameter. If the Promise is rejected, you can attach an error handler using the catch method, which will be called with the reason for the rejection.</p>
<p>Using Promises offers several advantages over traditional callback-based methods. For example, Promises can help prevent "callback hell," a common issue in asynchronous code where nested callbacks become hard to read and maintain.</p>
<p>Promises also make error handling in asynchronous code easier, as you can use the catch method to manage errors that occur anywhere in the Promise chain.</p>
<p>Finally, Promises can simplify your code by providing a consistent, composable way to handle asynchronous operations, regardless of their underlying implementation.</p>
<h3 id="heading-how-to-create-a-promise">How to Create a Promise</h3>
<p>Promise syntax:</p>
<pre><code class="lang-typescript"><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">// Do some asynchronous operation</span>
  <span class="hljs-comment">// If the operation is successful, call resolve with the result</span>
  <span class="hljs-comment">// If the operation fails, call reject with an error object</span>
});

myPromise
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-comment">// Handle the successful result</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-comment">// Handle the error</span>
  });
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// Example 1 on how to create a promise</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myAsyncFunction</span>(<span class="hljs-params"></span>): <span class="hljs-title">Promise</span>&lt;<span class="hljs-title">string</span>&gt; </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">// Some asynchronous operation</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-comment">// Successful operation resolves promiseCheck out my latest blog post on mastering async programming in TypeScript! Learn how to work with Promises, Async/Await, and Callbacks to write efficient and scalable code. Get ready to take your TypeScript skills to the next level!</span>
      <span class="hljs-keyword">const</span> success = <span class="hljs-literal">true</span>;

      <span class="hljs-keyword">if</span> (success) {
        <span class="hljs-comment">// Resolve the promise with the operation result if the operation was successful</span>
        resolve(
          <span class="hljs-string">`The result is success and your operation result is <span class="hljs-subst">${operationResult}</span>`</span>
        );
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">const</span> rejectCode: <span class="hljs-built_in">number</span> = <span class="hljs-number">404</span>;
        <span class="hljs-keyword">const</span> rejectMessage: <span class="hljs-built_in">string</span> = <span class="hljs-string">`The result is failed and your operation result is <span class="hljs-subst">${rejectCode}</span>`</span>;
        <span class="hljs-comment">// Reject the promise with the operation result if the operation failed</span>
        reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(rejectMessage));
      }
    }, <span class="hljs-number">2000</span>);
  });
}

<span class="hljs-comment">// Use the promise</span>
myAsyncFunction()
  .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 : The result is success and your operation result is 4</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 : The result is failed and your operation result is 404</span>
  });
</code></pre>
<p>In the example above, we have a function called <code>myAsyncFunction()</code> that returns a <code>promise</code>. We use the <code>Promise</code> constructor to create the promise, which takes a <code>callback function</code> with <code>resolve</code> and <code>reject</code> arguments. If the asynchronous operation is successful, we call the resolve function. If it fails, we call the reject function.</p>
<p>The promise object returned by the constructor has a <code>then()</code> method, which takes success and failure callback functions. If the promise resolves successfully, the success callback function is called with the result. If the promise is rejected, the failure callback function is called with an error message.</p>
<p>The promise object also has a <code>catch()</code> method used to handle errors that occur during the promise chain. The <code>catch()</code> method takes a callback function, which is called if any error occurs in the promise chain.</p>
<p>Now, let's move on to how to chain promises in TypeScript.</p>
<h3 id="heading-how-to-chain-promises">How to Chain Promises</h3>
<p>Chaining promises allows you to perform <code>multiple asynchronous operations</code> in sequence or in parallel. This is helpful when you need to carry out several async tasks one after another or at the same time. For instance, you might need to fetch data asynchronously and then process it asynchronously.</p>
<p>Let's look at an example of how to chain promises:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Example on how chaining promises works</span>
<span class="hljs-comment">// First promise</span>
<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-keyword">const</span> functionOne: <span class="hljs-built_in">string</span> = <span class="hljs-string">"This is the first promise function"</span>;
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(functionOne);
  }, <span class="hljs-number">1000</span>);
});

<span class="hljs-comment">// Second promise</span>
<span class="hljs-keyword">const</span> promise2 = <span class="hljs-function">(<span class="hljs-params">data: <span class="hljs-built_in">number</span></span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> functionTwo: <span class="hljs-built_in">string</span> = <span class="hljs-string">"This is the second second promise  function"</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-string">` <span class="hljs-subst">${data}</span>  '+'  <span class="hljs-subst">${functionTwo}</span> `</span>);
    }, <span class="hljs-number">1000</span>);
  });
};

<span class="hljs-comment">// Chaining first and second promises together</span>
promise1
  .then(promise2)
  .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: This is the first promise function + This is the second second promise function</span>
  })
  .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 the example above, we have two promises: <code>promise1</code> and <code>promise2</code>. <code>promise1</code> resolves after 1 second with the string "This is the first promise function." <code>promise2</code> takes a number as input and returns a promise that resolves after 1 second with a string that combines the input number and the string "This is the second promise function."</p>
<p>We chain the two promises together using the <code>then</code> method. The output <code>promise1</code> is passed as input to <code>promise2</code>. Finally, we use the <code>then</code> method again to log the output of <code>promise2</code> to the console. If either <code>promise1</code> or <code>promise2</code> rejects, the error will be caught by the <code>catch</code> method.</p>
<p>Congratulations! You have learned how to create and chain promises in TypeScript. You can now use promises to perform asynchronous operations in TypeScript. Now, let's explore how <code>Async/Await</code> works in TypeScript.</p>
<h2 id="heading-how-to-use-async-await-in-typescript">How to Use Async / Await in TypeScript</h2>
<p><strong>Async/await</strong> is a syntax introduced in ES2017 to make working with Promises easier. It allows you to write asynchronous code that looks and feels like synchronous code.</p>
<p>In TypeScript, you can define an asynchronous function using the <code>async</code> keyword. This tells the compiler that the function is asynchronous and will return a Promise.</p>
<p>Now, let's see how to use async/await in TypeScript.</p>
<p>Async / Await Syntax:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Async / Await Syntax in TypeScript</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">functionName</span>(<span class="hljs-params"></span>): <span class="hljs-title">Promise</span>&lt;<span class="hljs-title">ReturnType</span>&gt; </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> promise;
    <span class="hljs-comment">// code to execute after promise resolves</span>
    <span class="hljs-keyword">return</span> result;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-comment">// code to execute if promise rejects</span>
    <span class="hljs-keyword">throw</span> error;
  }
}
</code></pre>
<p>In the example above, <code>functionName</code> is an async function that returns a Promise of <code>ReturnType</code>. The <code>await</code> the keyword is used to wait for the promise to resolve before moving to the next line of code.</p>
<p>The <code>try/catch</code> block is used to handle any errors that occur while running the code inside the async function. If an error happens, it will be caught by the catch block, where you can handle it appropriately.</p>
<h3 id="heading-using-arrow-functions-with-async-await"><strong>Using Arrow Functions with Async / Await</strong></h3>
<p>You can also use arrow functions with async/await syntax in TypeScript:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> functionName = <span class="hljs-keyword">async</span> (): <span class="hljs-built_in">Promise</span>&lt;ReturnType&gt; =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> promise;
    <span class="hljs-comment">// code to execute after promise resolves</span>
    <span class="hljs-keyword">return</span> result;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-comment">// code to execute if promise rejects</span>
    <span class="hljs-keyword">throw</span> error;
  }
};
</code></pre>
<p>In the example above, <code>functionName</code> is defined as an arrow function that returns a Promise of <code>ReturnType</code>. The async keyword indicates that this is an asynchronous function, and the await keyword is used to wait for the promise to resolve before moving to the next line of code.</p>
<h3 id="heading-async-await-with-an-api-call"><strong>Async / Await with an API Call</strong></h3>
<p>Now, let's go beyond the syntax and fetch some data from an API using async/await.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> User {
  id: <span class="hljs-built_in">number</span>;
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">const</span> fetchApi = <span class="hljs-keyword">async</span> (): <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">void</span>&gt; =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</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">`Failed to fetch users (HTTP status code: <span class="hljs-subst">${response.status}</span>)`</span>
      );
    }

    <span class="hljs-keyword">const</span> data: User[] = <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);
    <span class="hljs-keyword">throw</span> error;
  }
};

fetchApi();
</code></pre>
<p>Here, we’re fetching data from the JSONPlaceholder API, converting it to JSON, and then logging it to the console. This is a real-world example of how to use async/await in TypeScript.</p>
<p>You should see user information in the console. This image shows the output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737554438217/a1b865ea-0903-4749-a079-c8401be05787.png" alt="a1b865ea-0903-4749-a079-c8401be05787" class="image--center mx-auto" width="2452" height="916" loading="lazy"></p>
<h3 id="heading-asyncawait-with-axios-api-call"><strong>Async/Await with Axios API call</strong></h3>
<pre><code class="lang-typescript"><span class="hljs-comment">// Example 2 on how to use async / await in typescript</span>

<span class="hljs-keyword">const</span> fetchApi = <span class="hljs-keyword">async</span> (): <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">void</span>&gt; =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(
      <span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>
    );
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.data;
    <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);
  }
};

fetchApi();
</code></pre>
<p>In the example above, we define the <code>fetchApi()</code> function using async/await and the <code>Axios.get()</code> method to make an HTTP GET request to the specified URL. We use await to wait for the response, then extract the data using the data property of the response object. Finally, we log the data to the console with <code>console.log()</code>. Any errors that occur are caught and logged to the console with <code>console.error()</code>.</p>
<p>We can achieve this using Axios, so you should see the same result in the console.</p>
<p>This image shows the output when using Axios in the console:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737554631796/4f85a12d-6a9b-4eaa-9ab9-910a8a463dc6.png" alt="4f85a12d-6a9b-4eaa-9ab9-910a8a463dc6" class="image--center mx-auto" width="2032" height="1047" loading="lazy"></p>
<p>Note: Before you try the code above, you need to install Axios using npm or yarn.</p>
<pre><code class="lang-bash">
npm install axios
</code></pre>
<pre><code class="lang-bash">
yarn add axios
</code></pre>
<p>If you're not familiar with Axios, you can <a target="_blank" href="https://www.npmjs.com/package/axios">learn more about it here</a>.</p>
<p>You can see that we used a <code>try</code> and <code>catch</code> block to handle errors. The <code>try</code> and <code>catch</code> block is a method for managing errors in TypeScript. So, whenever you make API calls like we just did, make sure you use a <code>try</code> and <code>catch</code> block to handle any errors.</p>
<p>Now, let's explore a more advanced use of the <code>try</code> and <code>catch</code> block in TypeScript:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Example 3 on how to use async / await in typescript</span>

<span class="hljs-keyword">interface</span> Recipe {
  id: <span class="hljs-built_in">number</span>;
  name: <span class="hljs-built_in">string</span>;
  ingredients: <span class="hljs-built_in">string</span>[];
  instructions: <span class="hljs-built_in">string</span>[];
  prepTimeMinutes: <span class="hljs-built_in">number</span>;
  cookTimeMinutes: <span class="hljs-built_in">number</span>;
  servings: <span class="hljs-built_in">number</span>;
  difficulty: <span class="hljs-built_in">string</span>;
  cuisine: <span class="hljs-built_in">string</span>;
  caloriesPerServing: <span class="hljs-built_in">number</span>;
  tags: <span class="hljs-built_in">string</span>[];
  userId: <span class="hljs-built_in">number</span>;
  image: <span class="hljs-built_in">string</span>;
  rating: <span class="hljs-built_in">number</span>;
  reviewCount: <span class="hljs-built_in">number</span>;
  mealType: <span class="hljs-built_in">string</span>[];
}

<span class="hljs-keyword">const</span> fetchRecipes = <span class="hljs-keyword">async</span> (): <span class="hljs-built_in">Promise</span>&lt;Recipe[] | <span class="hljs-built_in">string</span>&gt; =&gt; {
  <span class="hljs-keyword">const</span> api = <span class="hljs-string">"https://dummyjson.com/recipes"</span>;
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(api);

    <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">`Failed to fetch recipes: <span class="hljs-subst">${response.statusText}</span>`</span>);
    }

    <span class="hljs-keyword">const</span> { recipes } = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-keyword">return</span> recipes; <span class="hljs-comment">// Return the recipes array</span>
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error fetching recipes:"</span>, error);
    <span class="hljs-keyword">if</span> (error <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Error</span>) {
      <span class="hljs-keyword">return</span> error.message;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-string">"An unknown error occurred."</span>;
  }
};

<span class="hljs-comment">// Fetch and log recipes</span>
fetchRecipes().then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Array</span>.isArray(data)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Recipes fetched successfully:"</span>, data);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error message:"</span>, data);
  }
});
</code></pre>
<p>In the example above, we define an <code>interface Recipe</code> that outlines the structure of the data we expect from the API. We then create the <code>fetchRecipes()</code> function using async/await and the fetch() method to make an HTTP GET request to the specified API endpoint.</p>
<p>We use a <code>try/catch</code> block to handle any errors that might occur during the API request. If the request is successful, we extract the data property from the response using await and return it. If an error occurs, we check for an error message and return it as a string if it exists.</p>
<p>Finally, we call the <code>fetchRecipes()</code> function and use <code>.then()</code> to log the returned data to the console. This example demonstrates how to use <code>async/await</code> with <code>try/catch</code> blocks to handle errors in a more advanced scenario, where we need to extract data from a response object and return a custom error message.</p>
<p>This image shows the output result of the code:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737557515062/922592da-e9a6-4792-9d22-d5f8f8e84889.png" alt="922592da-e9a6-4792-9d22-d5f8f8e84889" class="image--center mx-auto" width="2431" height="1007" loading="lazy"></p>
<h3 id="heading-async-await-with-promiseall"><strong>Async / Await with Promise.all</strong></h3>
<p><code>Promise.all()</code> is a method that takes an array of promises as input (an iterable) and returns a single Promise as output. This Promise resolves when all the input promises have been resolved or if the input iterable contains no promises. It rejects immediately if any of the input promises are rejected or if non-promises throw an error, and it will reject with the first rejection message or error.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Example of using async / await with Promise.all</span>
<span class="hljs-keyword">interface</span> User {
  id: <span class="hljs-built_in">number</span>;
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  profilePicture: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">interface</span> Post {
  id: <span class="hljs-built_in">number</span>;
  title: <span class="hljs-built_in">string</span>;
  body: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">interface</span> Comment {
  id: <span class="hljs-built_in">number</span>;
  postId: <span class="hljs-built_in">number</span>;
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  body: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">const</span> fetchApi = <span class="hljs-keyword">async</span> &lt;T&gt;(url: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">Promise</span>&lt;T&gt; =&gt; {
  <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">if</span> (response.ok) {
      <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
      <span class="hljs-keyword">return</span> data;
    } <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">`Network response was not ok for <span class="hljs-subst">${url}</span>`</span>);
    }
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Error fetching data from <span class="hljs-subst">${url}</span>`</span>);
  }
};

<span class="hljs-keyword">const</span> fetchAllApis = <span class="hljs-keyword">async</span> (): <span class="hljs-built_in">Promise</span>&lt;[User[], Post[], Comment[]]&gt; =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> [users, posts, comments] = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all([
      fetchApi&lt;User[]&gt;(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>),
      fetchApi&lt;Post[]&gt;(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>),
      fetchApi&lt;Comment[]&gt;(<span class="hljs-string">"https://jsonplaceholder.typicode.com/comments"</span>),
    ]);
    <span class="hljs-keyword">return</span> [users, posts, comments];
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Error fetching data from one or more APIs"</span>);
  }
};

fetchAllApis()
  .then(<span class="hljs-function">(<span class="hljs-params">[users, posts, comments]</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Users: "</span>, users);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Posts: "</span>, posts);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Comments: "</span>, comments);
  })
  .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 the code above, we used <code>Promise.all</code> to fetch multiple APIs at the same time. If you have several APIs to fetch, you can use <code>Promise.all</code> to get them all at once. As you can see, we used <code>map</code> to loop through the array of APIs and then pass it to <code>Promise.all</code> to fetch them simultaneously.</p>
<p>The image below shows the output from the API calls:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737560380441/14bbecbb-7dad-464e-b412-028f56e9d679.png" alt="14bbecbb-7dad-464e-b412-028f56e9d679" class="image--center mx-auto" width="2442" height="996" loading="lazy"></p>
<p>Let's see how to use <code>Promise.all</code> with Axios:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Example of using async / await with axios and Promise.all</span>

<span class="hljs-keyword">const</span> fetchApi = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> urls = [
      <span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>,
      <span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>,
    ];
    <span class="hljs-keyword">const</span> responses = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all(urls.map(<span class="hljs-function">(<span class="hljs-params">url</span>) =&gt;</span> axios.get(url)));
    <span class="hljs-keyword">const</span> data = <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.data));
    <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);
  }
};

fetchApi();
</code></pre>
<p>In the example above, we're using <code>Promise.all</code> to fetch data from two different URLs at the same time. First, we create an array of URLs, then use the map to create an array of Promises from the <code>axios.get</code> calls. We pass this array to <code>Promise.all</code>, which returns an array of responses. Finally, we use the map again to get the data from each response and log it to the console.</p>
<h2 id="heading-how-to-use-callbacks-in-typescript">How to Use Callbacks in TypeScript</h2>
<p>A <strong>callback</strong> is a function passed as an argument to another function. The callback function is executed inside the other function. Callbacks ensure that a function doesn't run before a task is completed – but that it then runs right after the task finishes. They help us write asynchronous JavaScript code and prevent problems and errors.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Example of using callbacks in typescript</span>

<span class="hljs-keyword">const</span> add = (a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, callback: <span class="hljs-function">(<span class="hljs-params">result: <span class="hljs-built_in">number</span></span>) =&gt;</span> <span class="hljs-built_in">void</span>) =&gt; {
  <span class="hljs-keyword">const</span> result = a + b;
  callback(result);
};

add(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(result);
});
</code></pre>
<p>The image below shows the callback function:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737560660649/80203145-d053-49b8-a160-a1d72ed17a7a.png" alt="80203145-d053-49b8-a160-a1d72ed17a7a" class="image--center mx-auto" width="2451" height="545" loading="lazy"></p>
<p>Let's see another example of using callbacks in TypeScript:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Example of using a callback function in TypeScript</span>

<span class="hljs-keyword">type</span> User = {
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
};

<span class="hljs-keyword">const</span> fetchUserData = (
  id: <span class="hljs-built_in">number</span>,
  callback: <span class="hljs-function">(<span class="hljs-params">error: <span class="hljs-built_in">Error</span> | <span class="hljs-literal">null</span>, user: User | <span class="hljs-literal">null</span></span>) =&gt;</span> <span class="hljs-built_in">void</span>
) =&gt; {
  <span class="hljs-keyword">const</span> api = <span class="hljs-string">`https://jsonplaceholder.typicode.com/users/<span class="hljs-subst">${id}</span>`</span>;
  fetch(api)
    .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">return</span> response.json();
      } <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">"Network response was not ok."</span>);
      }
    })
    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      <span class="hljs-keyword">const</span> user: User = {
        name: data.name,
        email: data.email,
      };
      callback(<span class="hljs-literal">null</span>, user);
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      callback(error, <span class="hljs-literal">null</span>);
    });
};

<span class="hljs-comment">// Usage of fetchUserData with a callback function</span>
fetchUserData(<span class="hljs-number">1</span>, <span class="hljs-function">(<span class="hljs-params">error, user</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(user);
  }
});
</code></pre>
<p>In the example above, we have a function called <code>fetchUserData</code> that takes an <code>id</code> and a <code>callback</code> as parameters. This <code>callback</code> is a function with two parameters: an error and a user.</p>
<p>The <code>fetchUserData</code> function retrieves user data from a JSONPlaceholder API endpoint using the <code>id</code>. If the fetch is successful, it creates an <code>User</code> object and passes it to the callback function with a null error. If there's an error during the fetch, it sends the error to the callback function with a null user.</p>
<p>To use the <code>fetchUserData</code> function with a callback, we provide an <code>id</code> and a callback function as arguments. The callback function checks for errors and logs the user data if there are no errors.</p>
<p>The image below shows the output of the API calls:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737560996613/2b37fa46-1ee4-4dee-8d50-82c09a235aec.png" alt="2b37fa46-1ee4-4dee-8d50-82c09a235aec" class="image--center mx-auto" width="2457" height="1023" loading="lazy"></p>
<h3 id="heading-how-to-use-callbacks-responsibly">How to Use Callbacks Responsibly</h3>
<p>While callbacks are fundamental to asynchronous programming in TypeScript, they require careful management to avoid <strong>"callback hell"</strong> – the pyramid-shaped, deeply nested code that becomes hard to read and maintain. Here's how to use callbacks effectively:</p>
<ol>
<li><p><strong>Avoid deep nesting</strong></p>
<ul>
<li><p>Flatten your code structure by breaking complex operations into named functions</p>
</li>
<li><p>Use promises or async/await for complex async workflows (more on this below)</p>
</li>
</ul>
</li>
<li><p><strong>Error handling first</strong></p>
<ul>
<li><p>Always follow the Node.js convention of <code>(error, result)</code> parameters</p>
</li>
<li><p>Check for errors at every level of nested callbacks</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-typescript">    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processData</span>(<span class="hljs-params">input: <span class="hljs-built_in">string</span>, callback: (err: <span class="hljs-built_in">Error</span> | <span class="hljs-literal">null</span>, result?: <span class="hljs-built_in">string</span>) =&gt; <span class="hljs-built_in">void</span></span>) </span>{
      <span class="hljs-comment">// ... always call callback with error first</span>
    }
</code></pre>
<ol start="3">
<li><p><strong>Use type annotations</strong></p>
<ul>
<li><p>Leverage TypeScript's type system to enforce callback signatures</p>
</li>
<li><p>Define clear interfaces for callback parameters</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-typescript">    <span class="hljs-keyword">type</span> ApiCallback = <span class="hljs-function">(<span class="hljs-params">error: <span class="hljs-built_in">Error</span> | <span class="hljs-literal">null</span>, data?: ApiResponse</span>) =&gt;</span> <span class="hljs-built_in">void</span>;
</code></pre>
<ol start="4">
<li><p><strong>Consider control flow libraries</strong><br> For complex async operations, use utilities like <code>async.js</code> for:</p>
<ul>
<li><p>Parallel execution</p>
</li>
<li><p>Series execution</p>
</li>
<li><p>Error handling pipelines</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-when-to-use-callbacks-vs-alternatives">When to Use Callbacks vs. Alternatives</h3>
<p>There are times when callbacks are a great choice, and other times when they’re not.</p>
<p>Callbacks are helpful when you’re working with async operations (single completion), interfacing with older libraries or APIs that expect callbacks, handling event listeners (like click listeners or websocket events) or creating lightweight utilities with simple async needs.</p>
<p>In other scenarios where you need to focus on writing maintainable code with a clear async flow, callbacks cause trouble and you should prefer promises or async-await. For example, when you need to chain multiple operations, handle complex error propagation, work with modern APIs (like the Fetch API or FS Promises), or use <code>promise.all()</code> for parallel execution.</p>
<p><strong>Example migration from callbacks to promises:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Callback version</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchUser</span>(<span class="hljs-params">id: <span class="hljs-built_in">number</span>, callback: (err: <span class="hljs-built_in">Error</span> | <span class="hljs-literal">null</span>, user?: User) =&gt; <span class="hljs-built_in">void</span></span>) </span>{
  <span class="hljs-comment">// ... </span>
}

<span class="hljs-comment">// Promise version</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchUserAsync</span>(<span class="hljs-params">id: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">Promise</span>&lt;<span class="hljs-title">User</span>&gt; </span>{
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-comment">// Usage with async/await</span>
<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUserAsync(<span class="hljs-number">1</span>);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-comment">// Handle error</span>
}
</code></pre>
<h3 id="heading-the-evolution-of-async-patterns">The Evolution of Async Patterns</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Pattern</td><td>Pros</td><td>Cons</td></tr>
</thead>
<tbody>
<tr>
<td>Callbacks</td><td>Simple, universal</td><td>Nested complexity</td></tr>
<tr>
<td>Promises</td><td>Chainable, better error flow</td><td>Requires .then() chains</td></tr>
<tr>
<td>Async/Await</td><td>Sync-like readability</td><td>Requires transpilation</td></tr>
</tbody>
</table>
</div><p>Modern TypeScript projects often use a mix: callbacks for event-driven patterns and promises/async-await for complex async logic. The key is choosing the right tool for your specific use case while maintaining code clarity.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we have learned about the different ways to handle asynchronous code in TypeScript. We have learned about callbacks, promises, async/await, and how to use them in TypeScript. We have also learned about this concept.</p>
<p>If you want to learn more about programming and how to become a better software engineer, you can subscribe to my YouTube channel <a target="_blank" href="https://www.youtube.com/@CliffTech/videos">CliffTech</a>.</p>
<p>Thank you for reading my article. I hope you enjoyed it. If you have any questions, feel free to reach out to me.</p>
<p>Connect with me on social media:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Clifftech_Dev">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/Clifftech123">Github</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/isaiah-clifford-opoku-a506a51b2/">Linkedin</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Asynchronous Programming Works in Rust – Futures and Async/Await Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ If you're familiar with languages like JavaScript and Python, you may have heard about asynchronous programming. And perhaps you're wondering how it works in Rust. In this article, I'll give you a simple overview of how asynchronous programming works... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-asynchronous-programming-works-in-rust/</link>
                <guid isPermaLink="false">66be1c3ab712ab343b0b9150</guid>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oduah Chigozie ]]>
                </dc:creator>
                <pubDate>Thu, 15 Aug 2024 15:18:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723746256888/b046d857-161c-41be-96d0-1c05b1e448b8.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're familiar with languages like JavaScript and Python, you may have heard about asynchronous programming. And perhaps you're wondering how it works in Rust.</p>
<p>In this article, I'll give you a simple overview of how asynchronous programming works in Rust. You'll learn about futures as well as <code>async</code>/<code>.await</code>.</p>
<p>This article isn't a beginner's guide to Rust or asynchronous programming, so you'll need to have some experience with programming in Rust and familiarity with asynchronous programming to get the most out of this guide.</p>
<p>With that said, let's begin!</p>
<h2 id="heading-when-should-you-use-asynchronous-programming">When Should You Use Asynchronous Programming?</h2>
<p>Asynchronous tasks work like a more integrated version of threads. You can use them in a lot of the same scenarios where you can use multiple threads. The benefits async programming provides over multiple threads is that multi-threaded applications have a larger overhead to work on multiple tasks compared to asynchronous applications.</p>
<p>But this doesn’t make asynchronous applications better than multithreaded applications. Multi-threaded programs can run multiple computing-intensive tasks simultaneously – and multiple times faster than if you ran all the tasks in a single thread.</p>
<p>With asynchronous coding, trying to run multiple computing-intensive applications simultaneously will be much slower than just running every task on a single thread.</p>
<p>Asynchronous programming is very good for building applications that make many network requests or many IO operations like file reading and writing.</p>
<p>I can’t cover every case when you’ll want to use asynchronous techniques. But I can say that it’s most beneficial for tasks that have a lot of idle time (for example, waiting for a server to respond to a network request).</p>
<p>During the idle time of an asynchronous task, instead of blocking the thread, the event handler works on other tasks in the program until the asynchronous task is ready to make progress.</p>
<h2 id="heading-overview-of-asynchronous-rust-futures">Overview of Asynchronous Rust – Futures</h2>
<p>The basics of asynchronous Rust are Futures. Futures are similar to promises in JavaScript. They are Rust's way of saying "hey, I'm going to give you the result later, but just hold on to this (the future instance) to keep track of if the result is ready."</p>
<p>Futures are traits, with a <code>poll</code> state that is either <code>Poll::Pending</code> to signify that the future is in the process of executing its task, or <code>Poll::Ready</code> to signify that the future is done with its task.</p>
<p>Futures are lazy. They run when you <code>.await</code> them (we'll look into how to <code>.await</code> them in the next section). <code>.await</code>ing a future pauses the execution of an asynchronous thread, and begins running its task. At this point the result of the <code>poll</code> method is <code>Poll::Pending</code>. When the future is done with its task, <code>poll</code>'s state will become <code>Poll::Ready</code>, and the future will allow it's thread to proceed.</p>
<p>If you want to get more into the technical details about Futures, you can check out <a target="_blank" href="https://rust-lang.github.io/async-book/02_execution/01_chapter.html">the documentation</a>.</p>
<h2 id="heading-asyncawait-in-rust">async/.await in Rust</h2>
<p><code>async</code> and <code>.await</code> are the primary ways you'll be working with asynchronous code in Rust. <code>async</code> is a keyword for declaring asynchronous functions. Within those functions, the <code>.await</code> keyword pauses its execution until the result of the future is ready.</p>
<p>Let's take a look at an example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add</span></span>(a: <span class="hljs-built_in">u8</span>, b: <span class="hljs-built_in">u8</span>) -&gt; <span class="hljs-built_in">u8</span> {
    a + b
}

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

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

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

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">let</span> result = block_on(add(a, b));
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{result}"</span>); 
}
</code></pre>
<p>First, we import the <code>block_on</code> method on the first line and use the method to block the main thread until the result of the <code>add(a, b)</code> function was ready. We also didn’t have to make the <code>main</code> function asynchronous like we did with <code>tokio</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Asynchronous programming allows you to run operations in parallel and with less overhead and complexity compared to traditional multi-threading. In Rust, it allows you to build I/O and network applications more efficiently.</p>
<p>While this article should help you become familiar with the basics asynchronous programming in Rust, it’s still just an overview. There are some cases where you'll need to use other constructs in Rust like Pinning, Arcs, and so on.</p>
<p>If you have any questions or thoughts, feel free to reach out to me. Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use React Suspense to Improve your React Projects ]]>
                </title>
                <description>
                    <![CDATA[ React's ecosystem is always growing, and it seems like there are always new features and enhancements to make development more effective and user-friendly. React Suspense is one such feature that has become quite popular among React devs. In this gui... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-suspense/</link>
                <guid isPermaLink="false">66d46090f855545810e934bb</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Okosa Leonard ]]>
                </dc:creator>
                <pubDate>Thu, 16 Nov 2023 17:04:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/pexels-pixabay-289323.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React's ecosystem is always growing, and it seems like there are always new features and enhancements to make development more effective and user-friendly.</p>
<p>React Suspense is one such feature that has become quite popular among React devs.</p>
<p>In this guide, you'll learn all about React Suspense and examine its features, use cases, and potential to transform your web applications.</p>
<h2 id="heading-what-is-react-suspense">What is React Suspense?</h2>
<p>React suspense is a new feature released in React.js version 16.6. With this new feature, components may pause rendering while they wait for an asynchronous process to finish, like separating code or retrieving data.</p>
<p>Suspense was created to make it easier for developers to create apps that have improved loading indications and a more cohesive user experience. It makes it possible to halt component tree rendering until specific criteria are satisfied, which makes it easier for developers to work with asynchronous data.</p>
<h3 id="heading-a-problem-that-loading-states-face-in-react">A Problem That Loading States Face in React</h3>
<p>Managing loading states in React was a little trickier prior to React Suspense. Developers had to implement the loading mechanism using third-party frameworks like Redux or Mobx, conditional rendering, or state management. This frequently resulted in complicated, error-prone code.</p>
<p>This problem was solved by React Suspense, which offers a more sophisticated and integrated method of managing asynchronous actions and loading states.</p>
<h2 id="heading-key-concepts-and-features-of-react-suspense">Key Concepts and Features of React Suspense</h2>
<p>Let's talk about some concepts and features to help you understand React Suspense and how it works.</p>
<h3 id="heading-1-suspense-component">1) Suspense Component</h3>
<p>An essential element of React Suspense is the Suspense component. It lets you declare how to handle fallback content while asynchronous actions are pending and encapsulate any portion of your component tree.</p>
<pre><code class="lang-jsx">&lt;Suspense fallback={<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">LeoFallback</span> /&gt;</span></span>}&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">LeoComponent</span> /&gt;</span></span>
&lt;/Suspense&gt;
</code></pre>
<p>In this use case, if the <code>LeoComponent</code> is not ready, React will display the <code>LeoFallback</code> component instead.</p>
<h3 id="heading-2-using-reactlazy-or-lazy">2) Using <code>React.lazy()</code> or <code>lazy()</code></h3>
<p>React has a dynamic import mechanism called <code>lazy()</code> that lets you load components in a lazy manner.</p>
<p>Basically, lazy loading refers to the requirement that a component or portion of code will load only when it's needed. This functionality, which was first included in React 16.6, is frequently used in conjunction with React Suspense to enhance web application speed by loading components only when needed.</p>
<p>This is very helpful for minimizing your application's loading speed and lowering the initial bundle size.</p>
<p>Now we'll investigate <code>lazy()</code> in further depth and learn how it works.</p>
<h4 id="heading-basic-syntax-of-lazy">Basic Syntax of <code>lazy()</code></h4>
<p>To use <code>lazy()</code>, you have to follow these steps:</p>
<p>First, import the <code>Suspense</code> components from React, as well as any components you intend to load lazily.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
</code></pre>
<p>Then use <code>lazy()</code> to define a dynamic import. For the component you wish to load slowly, this function accepts an argument that is a function that produces a dynamic import statement.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> LeoComponent = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./LeoComponent'</span>));
</code></pre>
<p>In this use case, the <code>LeoComponent</code> will be loaded lazily when it's needed. The dynamic <code>import()</code> statement specifies the path to the component you want to import.</p>
<p>Next, enclose the element you wish to load lazily in a Suspense element. You may designate a backup component to show while the lazy-loaded component is being retrieved by using the Suspense component.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">LeoComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, while the <code>LeoComponent</code> is being fetched, the fallback component will be displayed, indicating that the content is loading.</p>
<h4 id="heading-advantages-of-reactlazy">Advantages of <code>React.lazy()</code></h4>
<ol>
<li><p>Enhanced speed: By selectively loading the components needed for the current view and not loading all of the components at once, lazy loading of components can enhance the speed of the application.</p>
</li>
<li><p>Improved User Experience: You may improve the user experience by informing users that the application is actively loading material by utilizing Suspense to display a loading indication.</p>
</li>
<li><p>Code Splitting: One of <code>lazy()</code>'s main advantages is that it makes code splitting possible. The process of code splitting involves breaking up the code of your application into smaller, on-demand bundles. This minimizes the initial bundle size and quickens your application's loading time.</p>
</li>
</ol>
<p>With <code>lazy()</code>, you can do code splitting and lazy loading of components in your React apps. This is a great feature. It is a useful tool for streamlining your web applications' efficiency and loading times, improving user experience by loading components only when needed.</p>
<p>It has restrictions and certain concerns, but when utilized properly, it may be a useful tool in your toolset for React development.</p>
<h3 id="heading-3-error-boundaries">3) Error Boundaries</h3>
<p>React components known as error boundaries have the ability to detect and manage faults inside their subtree. Because they can gently manage any problems that arise while waiting for asynchronous data, they are essential for dealing with suspense.</p>
<pre><code class="lang-jsx"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ErrorBoundary</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  componentDidCatch(error, info) {
    <span class="hljs-comment">// Handle the error</span>
  }

  render() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.props.children;
  }
}
</code></pre>
<h3 id="heading-4-what-is-concurrent-rendering">4) What is Concurrent Rendering?</h3>
<p>React Suspense was introduced as part of Concurrent Mode, which is an experimental set of features in React. Later on, concurrent rendering was introduced.</p>
<p>Concurrent rendering enables the execution of numerous tasks at once, improving the responsiveness and efficiency of React apps. It is a component of Concurrent Mode, a trial-and-error collection of features designed to overcome some of the drawbacks of conventional React rendering.</p>
<p>Ensuring that the user interface stays fluid and responsive even when React is handling complicated rendering or other asynchronous operations is the core objective of concurrent rendering.</p>
<h2 id="heading-how-does-react-suspense-work">How Does React Suspense Work?</h2>
<p>When using React Suspense with asynchronous operations, it follows these steps:</p>
<ol>
<li><p>After React loads, a component tree is rendered.</p>
</li>
<li><p>React looks to see whether any of its child components are in a suspended state when it comes across a Suspense component.</p>
</li>
<li><p>React will display the given fallback UI until the data is ready, if a child component is awaiting data (for example, as a result of a <code>lazy()</code> import or a data fetch).</p>
</li>
<li><p>React smoothly transitions to rendering the real content once the data is available.</p>
</li>
</ol>
<p>Because this procedure is automated, handling asynchronous actions without coding sophisticated logic is significantly easier for developers.</p>
<h2 id="heading-use-cases-for-react-suspense">Use Cases for React Suspense</h2>
<p>React Suspense is a flexible tool for your toolbox that may be used in a variety of scenarios, which include:</p>
<h3 id="heading-1-data-fetching">1. Data Fetching</h3>
<p>React Suspense's data fetching feature makes managing asynchronous data loading in your React apps easier. React Suspense allows you to postpone rendering until the data is available, enhancing user experience by offering fallback content or loading indications.</p>
<p>I'll give an example using a fake API to show how to retrieve data using React Suspense.</p>
<p>Here's how to use React Suspense to manage data loading, assuming you're using a framework like React Query or Relay for data fetching:</p>
<h4 id="heading-establish-error-boundary-and-react-suspense">Establish Error Boundary and React Suspense</h4>
<p>To capture any failures during data retrieving, you must first set up an error boundary and a React Suspense component. Here's how to make a custom <code>ErrorBoundary</code> component in react for data fetching:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ErrorBoundary</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  producer(props) {
    unique(props);
    <span class="hljs-built_in">this</span>.state = { <span class="hljs-attr">hasError</span>: <span class="hljs-literal">false</span> };
  }

  <span class="hljs-keyword">static</span> getDerivedStateFromError(error) {
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">hasError</span>: <span class="hljs-literal">true</span> };
  }

  render() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.state.hasError) {
      <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Error: Something is wrong!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
    }

    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.props.children;
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ErrorBoundary;
</code></pre>
<h4 id="heading-use-react-query-to-fetch-data">Use React Query to Fetch Data</h4>
<p>If you're using React Query to retrieve data, you can make a component that uses <code>useQuery</code> to retrieve data and wrap it in <code>Suspense</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { useQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-query'</span>;
<span class="hljs-keyword">import</span> ErrorBoundary <span class="hljs-keyword">from</span> <span class="hljs-string">'./ErrorBoundary'</span>;

<span class="hljs-comment">// Define your data-fetching function</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">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">'Network response was not ok'</span>);
  }
  <span class="hljs-keyword">return</span> response.json();
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">DataFetching</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { data, isLoading, isError } = useQuery(<span class="hljs-string">'data'</span>, fetchData);

  <span class="hljs-keyword">if</span> (isLoading) {
    <span class="hljs-keyword">throw</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">2000</span>)); <span class="hljs-comment">// Simulate loading delay</span>
  }

  <span class="hljs-keyword">if</span> (isError) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Error while fetching data'</span>);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Fetching data with React Suspense<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{data}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Leo's App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ErrorBoundary</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">React.Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
          <span class="hljs-tag">&lt;<span class="hljs-name">DataFetchingComponent</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">React.Suspense</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ErrorBoundary</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In this example, we fetch data using React Query's <code>useQuery</code> hook. To display the loading indicator, we <code>throw in new Promise</code> to mimic a loading delay if the data is still loading ( <code>isLoading is true</code> ). We throw an error so that the error boundary can catch it if there is a problem.</p>
<p>You can provide a backup component to display while loading by enclosing the <code>DataFetching</code> component in <code>Suspense</code>. It's a straightforward "Loading..." message in this instance.</p>
<p>You'll also want to ensure that the error handling, loading indications, and data fetching function are all customized according to your unique data-fetching needs.</p>
<p>This example shows how React Suspense makes state management and data fetching easier, leading to a more organized and understandable codebase.</p>
<p>These are examples of Suspense being used in a data fetching scenario in React.</p>
<h3 id="heading-2-lazy-loading-in-react-suspense">2. Lazy Loading in React Suspense</h3>
<p>Loading components of your application only when needed (lazy loading, also known as code splitting) can lower the size of your initial bundle and speed up the loading of your React application.</p>
<p>You can use <code>React.lazy()</code> in conjunction with React <code>Suspense</code> to easily include lazy loading into your application.</p>
<p>Here are the steps to implement lazy loading with React suspense:</p>
<p>First, import React Suspense from React:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
</code></pre>
<p>Next, create a lazy loaded component in your React app. To construct a component that loads slowly, use the <code>React.lazy()</code> method. Provide an arrow function to dynamically import the component.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> LennyComponent = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./LennyComponent'</span>));
</code></pre>
<p>Then wrap your component with a <code>Suspense</code>. Wrap Suspense around the sluggish part. While the lazy component is loading, you may designate a loading indication or fallback component to be shown.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Leo's App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">LennyComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>The component can be used like any other component in your React application.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">LennyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>This component is lazily loaded.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p>To finish building your application, you must use a development server and a tool like Webpack to build and serve your application in order to ensure that code splitting functions as intended. Your code will be automatically divided into pieces using Webpack for lazy loading.</p>
<p>This setup will minimize the initial bundle size and speed up the loading of your React application by only loading the <code>LazyComponent</code> when needed. While the component is being retrieved, users will see the loading indication (in this example, "Loading..."). The component loads and is rendered in the application with ease.</p>
<h3 id="heading-3-better-user-experiences">3. Better User Experiences</h3>
<p>React Suspense can be employed to ensure a smooth user experience by showing loading indicators or fallback content during data loading. This reduces the perceived loading time for people who are using your React application.</p>
<p>For example, let's say you have a component that fetches data from an API using <code>fetch</code> and you want to display a loading spinner while the data is being fetched. Here's a basic example using React Suspense:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-comment">// A component that fetches data</span>
<span class="hljs-keyword">const</span> fetchApiData = <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-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      resolve(<span class="hljs-string">'Data loaded!'</span>);
    }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Simulating a 2-second delay for data fetching</span>
  });
};

<span class="hljs-comment">// A component that uses Suspense to handle asynchronous data fetching</span>
<span class="hljs-keyword">const</span> DataComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> apidata = fetchApiData(); <span class="hljs-comment">// This can be any async function, like an API call</span>

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{apiData}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
};

<span class="hljs-comment">// Wrapping the component with Suspense</span>
<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">LoadingSpinner</span> /&gt;</span>}&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">DataComponent</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>
  );
};

<span class="hljs-comment">// A simple loading spinner component</span>
<span class="hljs-keyword">const</span> LoadingSpinner = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
};
</code></pre>
<p>In this instance:</p>
<p>The <code>fetchApiData</code> method is used by the <code>DataComponent</code> component to get data. Keep in mind that while <code>fetchApiData</code> is really a straightforward function that returns a promise, it may actually be an API call in practical applications.</p>
<p>The Suspense component, which requires a fallback argument, encapsulates the App component. One component that will be displayed while the asynchronous operation is running is the fallback prop. It's the <code>LoadingSpinner</code> component in this instance.</p>
<p>React Suspense will take care of the asynchronous data fetching automatically when the <code>DataComponent</code> is rendered. The <code>LoadingSpinner</code> component will render if the data is not yet accessible. After the data is retrieved, the user interface is updated.</p>
<p>This method eliminates the need for manual loading state management, making for a more seamless user experience. This code is straightforward and React Suspense works efficiently here.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>React Suspense is a major addition to the React ecosystem. It provides a simpler, integrated method of managing asynchronous actions and loading states. You can use it to design apps that offer quicker loading times, more efficient data fetching, and better user experiences by utilizing <code>Suspense</code>, <code>React.lazy()</code>, and error boundaries.</p>
<p>It's critical to comprehend the capabilities, restrictions, and best practices of any strong instrument. Concurrent Mode and React Suspense have the power to revolutionize web application development and improve user experience even more. But as the React ecosystem continues to grow, it's imperative to keep up with the most recent advancements and industry best practices.</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 JavaScript’s Asynchronous Operations Work in the Browser ]]>
                </title>
                <description>
                    <![CDATA[ By Amazing Enyichi Agu JavaScript is a popular programming language used for developing interactive front-end web applications, among other things.  It's widely known for its major features: it is single-threaded, non-blocking, and asynchronous. But ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-asynchronous-operations-in-the-browser/</link>
                <guid isPermaLink="false">66d45e3fbc9760a197a1037c</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 16 May 2023 21:58:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/pankaj-patel-1IW4HQuauSU-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Amazing Enyichi Agu</p>
<p>JavaScript is a popular programming language used for developing interactive front-end web applications, among other things. </p>
<p>It's widely known for its major features: it is <em>single-threaded</em>, <em>non-blocking</em>, and <em>asynchronous</em>. But what do these three things mean?</p>
<h3 id="heading-what-does-single-threaded-mean">What Does "Single-Threaded" Mean?</h3>
<p>When a programming language is referred to as single-threaded, it means the language can execute only one instruction at a time. This differs from multi-threaded programming languages that run multiple instructions at once.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/single-and-multi-threads.png" alt="Illustration depicting Single-threaded and Multi-threaded processes" width="600" height="400" loading="lazy">
<em>Illustration depicting Single-threaded and Multi-threaded processes</em></p>
<h3 id="heading-what-does-non-blocking-mean">What Does "Non-Blocking" Mean?</h3>
<p>When a programming language is said to be non-blocking, it means that the language does not wait for a specific previous instruction to finish executing before it moves to the next one. This ensures that no instruction blocks or obstructs the execution of subsequent instructions. </p>
<p>If a programming language is not non-blocking, it could lead to slow applications.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/asynchronous-javascript---Page-2.png" alt="Illustration of JavaScript’s non-blocking behavior" width="600" height="400" loading="lazy">
<em>Illustration of JavaScript’s non-blocking behavior</em></p>
<h3 id="heading-what-does-asynchronous-mean">What Does "Asynchronous" Mean?</h3>
<p>JavaScript is also asynchronous (async), which means that it can handle a large number of tasks at a time. This is a feature of multi-threaded programming languages, but JavaScript achieves it with a single thread.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/asynchronous-javascript---Page-3.png" alt="Illustration of the asynchronous process" width="600" height="400" loading="lazy">
<em>Illustration of the asynchronous process</em></p>
<p>Now, these features of JavaScript might seem contradictory. How can a language that is supposed to execute only one task at a time (Single-threaded) be able to handle a large number of tasks (asynchronous) simultaneously?</p>
<p>In this article, you will gain an understanding of how JavaScript manages to remain single-threaded despite executing asynchronous operations in the browser. We will also explore some concepts necessary for understanding the process.</p>
<p>This article assumes that you have basic knowledge of JavaScript and can apply it to Web Applications. The article covers the steps JavaScript takes to handle async operations in the browser. It does not go into detail to teach the different async functions there are, or how to write them. It only covers their process of execution in the browser.</p>
<p>The exciting part of all of this is that the article tells a short story, and uses this story as an analogy to explain the process. Through this unique approach, you will gain more insight into the inner workings of asynchronous operations.</p>
<p>Here's what we'll cover:</p>
<ol>
<li><a class="post-section-overview" href="#heading-the-story">The story that will help explain these concepts</a></li>
<li><a class="post-section-overview" href="#heading-how-the-javascript-engine-works">How the JavaScript engine works</a></li>
<li><a class="post-section-overview" href="#heading-how-the-call-stack-works">How the call stack works</a></li>
<li><a class="post-section-overview" href="#heading-asynchronous-operations-and-web-apis">Asynchronous operations and web APIs</a></li>
<li><a class="post-section-overview" href="#heading-callbacks">Callbacks</a></li>
<li><a class="post-section-overview" href="#heading-callback-queue">Callback queue</a></li>
<li><a class="post-section-overview" href="#heading-event-loops">Event loops</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-the-story">The Story</h2>
<p>This is the story of two companies. One of them is called <em>Lerdorf Corp</em> while the other is <em>Eich Agency</em>. These two companies are Event Planning Agencies and they cater to clients who need professional event planning services.</p>
<p>Lerdorf Corp is a long-running and successful company. They have a lot of staff and multiple specialized departments who work together to make sure they remain profitable. These departments include Catering, Registration and Ticketing, Accounting, and more.</p>
<p>When Lerdorf Corp secures a contract with a client, their efficient work process kicks into gear. The company swiftly breaks down the project into manageable tasks and assigns them to the respective departments responsible for their execution. This seamless division of labor ensures that each department can focus on its specific area of expertise, working in sync to deliver results.</p>
<p>This operational approach Lerdorf Corp employs is similar to how <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_concurrent_and_parallel_programming_languages#Multi-threaded">Multi-threaded Programming Languages</a> function. In Multi-threaded programming, a program can be split into separate <a target="_blank" href="https://en.wikipedia.org/wiki/Thread_(computing)">threads</a>, with each executing independently of the others.</p>
<p>Returning to our story, let's now shift our focus to the Eich Agency. It's a small agency with limited staff. Despite their ambitious aspirations, it may seem quite laughable that they aim to compete with the well-established Lerdorf Corp.</p>
<p>Lerdorf Corp initially did not see them as a competition. They gave Eich Agency a month or two to move out of business. Eich Agency did not have any specialized departments. Yet, they were successfully able to execute big events, exactly the size one would think only Lerdorf Corp could pull off. Eich Agency’s client base also steadily expanded over time.</p>
<p>Lerdorf Corp did not understand how this could be the case. It was clear to them that Eich Agency did not have sufficient resources. They struggled to make sense of the situation and eventually held a meeting concerning the issue.</p>
<p>During the meeting, they decided to investigate how Eich Agency was able to execute events for clients so quickly without enough resources. Lerdorf decided to designate a capable staff member to conduct an extensive investigation of the agency and compile a comprehensive report within one week. </p>
<p>After one week, the report was completed, and the executive staff at Lerdorf Corp reviewed it together.</p>
<h2 id="heading-how-the-javascript-engine-works">How the JavaScript Engine Works</h2>
<p>With the investigation, it turned out that Eich Agency had a core team. The team received requests for planning events for clients. Now that team was responsible for most of the planning. They generated a blueprint for how an event would work out.</p>
<p>The Eich Agency team usually ordered the small tasks they needed to execute into a roadmap, then they'd start from the top to bottom, executing them in order. They did this because they did not have separate departments dedicated to a set of tasks like Lerdorf Corp.</p>
<p>JavaScript executes instructions similar to how Eich Agency does it. For a browser to interpret JavaScript code, it needs to have a <a target="_blank" href="https://en.wikipedia.org/wiki/JavaScript_engine">JavaScript engine</a>. This JavaScript engine is a software component of a modern web browser that accepts JavaScript code, analyzes it, and transforms it into instructions the device will understand. The JavaScript engine can be likened to the core team of Eich Agency.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/asynchronous-javascript---Page-1.png" alt="JavaScript Engine inside the Runtime" width="600" height="400" loading="lazy">
<em>JavaScript Engine inside the Runtime</em></p>
<p>The JavaScript runtime is the environment that contains all the resources necessary for the execution of a JavaScript program. It includes the JavaScript Engine but also includes other things we will look at.</p>
<p>Different browsers today use different JavaScript engines. For example, the Chrome Browser uses the <a target="_blank" href="https://v8.dev/">V8 Engine from Google</a>, Firefox uses one called <a target="_blank" href="https://spidermonkey.dev/">Spidermonkey</a>, and Opera Browser previously used the <a target="_blank" href="https://dev.opera.com/blog/carakan/">Carakan</a> engine, before switching to V8.</p>
<p>These engines have individual differences, but their jobs still remain the same. They process JavaScript Code.</p>
<h2 id="heading-how-the-call-stack-works">How the Call Stack Works</h2>
<p>As the staff of Lerdorf Corp reviewed the report, they made an intriguing discovery. Eich Agency, upon finalizing the sequence of preparatory tasks for an upcoming event, would display the list on their board. With this order in place, the core team knew what task to start with and what to continue with.</p>
<p>The board Eich Agency uses to publicly list the order of tasks is similar to the Call Stack in the JavaScript Engine. The call stack is a component of a JavaScript Engine that keeps track of all the functions the program executes. It is a <a target="_blank" href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)">Stack</a> data structure that operates with two key operations.</p>
<p>These operations are:</p>
<ul>
<li>Push: This operation adds or pushes a new function onto the top of the stack. The stack can only add new entries to the top.</li>
<li>Pop: This operation removes or pops a new function off of the top of the stack. The Stack can only remove new entries from the top.</li>
</ul>
<p><strong>Last In First Out (LIFO)</strong> is a term that summarizes how the call stack works. The last operation that went in is the first operation that will leave the stack.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/asynchronous-javascript---Page-2--1-.png" alt="Simple Illustration of the Call Stack" width="600" height="400" loading="lazy">
<em>Simple Illustration of the Call Stack</em></p>
<p>After the JavaScript Engine receives JavaScript code, it parses the code and places the first function it encounters on the call stack. If, while executing that function, the JavaScript engine notices that it calls other functions, then those functions are stacked on top of the call stack. This is very important for functions nested in other functions as well as recursive functions.</p>
<p>The call stack makes it possible to track the current and future running functions essential for the execution of a program. For the stack to pop off a function, the engine must have finished interpreting and running that function. If not, it remains there. A peek at the JavaScript call stack during the execution of a program shows the current state of the program.</p>
<p>For example, consider these JavaScript instructions.</p>
<pre><code class="lang-javascript"><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-built_in">console</span>.log(<span class="hljs-string">"Hello World"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span>(<span class="hljs-params"></span>) </span>{
    greeting()
}

run()
</code></pre>
<p>Upon execution of the code, the call stack can look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/asynchronous-javascript---Page-2--2-.png" alt="The Call Stack while monitoring functions" width="600" height="400" loading="lazy">
<em>The Call Stack while monitoring functions</em></p>
<p>To recap, whenever the JavaScript engine receives code, it parses it and uses a call stack to monitor the execution of these instructions. This is similar to the way Eich Agency displays the order of tasks they need to accomplish.</p>
<h2 id="heading-asynchronous-operations-and-web-apis">Asynchronous Operations and Web APIs</h2>
<p>The way the Eich Agency core team ordered the tasks they wanted to execute was not strange to Lerdorf Corp at all. They themselves as a company employed a similar strategy when they wanted to work for clients, but there were some distinctions.</p>
<p>In Lerdorf, whenever they got a contract, the first thing they did was break the task into a few smaller chunks. After they broke it down, they sent those chunks to different departments they had. They had a lot of departments and the process was faster if those departments started working on the tasks independently.</p>
<p>Lerdorf Corp already had each individual department with their own board similar to the one Eich Agency used. The departments used it to keep track of the tasks to accomplish. </p>
<p>Relating it to JavaScript terms, they had many “call stacks” that operated independently. Meanwhile, the Eich Agency had only one “call stack”.</p>
<p>This revelation puzzled the Lerdorf Corp team more. How then did Eich Agency manage to host large events properly if they pretty much had just a single department? This was the question on everyone’s mind.</p>
<p>Upon further review of the report, the Lerdorf team made a shocking discovery. They discovered that the core team at Eich Agency did not actually do all the work themselves. They did not have a Catering or Audio-Visual department, while these were departments Lerdorf Corp had.</p>
<p>But based on the contracts Eich Agency secured, they were typically expected to provide these services. When drafting their lists of tasks, they included the provision of these services, even though the agency could not provide them in-house.</p>
<p>Here's what they did instead: while executing their tasks, whenever Eich Agency encountered a task they could not immediately execute, they took action. They contacted a different company offering that specific service and requested help. After contacting the company, they returned to their order of tasks.</p>
<p>If, while following their list of tasks, they encountered another assignment that they couldn't perform, they repeated the process. They would find a separate service provider, discuss their needs with them, and request the required service.</p>
<p>Relating this to JavaScript, even though JavaScript is single-threaded, it is also asynchronous. In asynchronous programming, a language can execute multiple tasks simultaneously. Just like Eich Agency, whenever JavaScript encounters asynchronous instructions like requests to third-party sites, or timer-based actions, it seeks assistance. </p>
<p>To achieve this, JavaScript uses the browser’s provided <strong>Web Application Programming Interfaces (Web APIs).</strong></p>
<p>One very important reason for writing asynchronous code is to prevent a scenario where a particular running function ends up blocking the rest of the code. If this happens, it can cause undesirable user experiences and make our software inefficient.</p>
<p>The Web APIs are a set of functions provided by the browser that the JavaScript engine can utilize. They include examples such as Document Object Model (DOM) manipulation methods, <code>fetch</code>, <code>setInterval</code>, <code>setTimeout</code>, promises, async-await functions, and more.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/asynchronous-javascript---Page-2--3-.png" alt="The JavaScript Engine interacting with the Web API" width="600" height="400" loading="lazy">
<em>The JavaScript Engine interacting with the Web APIs</em></p>
<h3 id="heading-callbacks">Callbacks</h3>
<p>Let us briefly go back to the story of Lerdorf Corp and Eich Agency. Recall that Eich Agency contracted service providers and requested their assistance, and then continued with their order of execution.</p>
<p>Whenever any of the external service providers called back the agency to deliver a response, such as notifying the completion of a request, the agency would later act upon this new information. </p>
<p>Lerdorf Corp discovered that even though the external providers handled and completed many services, the agency's core team still needed to take further action.</p>
<p>For example, let's say the core team of Eich Agency had requested a catering service provider to supply a certain quantity of snacks and drinks. The core team would still be responsible for collecting the snacks from the caterers and incorporating them into their inventory of items for the event. In this scenario, the snacks would join other items that Eich Agency had prepared for the event.</p>
<p>This is similar to how JavaScript works in the browser. Asynchronous operations provide a response after being processed using Web APIs. The purpose of writing an asynchronous function is to utilize the function's output for subsequent operations. We refer to the functions that rely on the response from asynchronous operations as callback functions.</p>
<p>A callback function is a function that is passed as an argument to a parent function, which the parent function needs to invoke after completing its process. In JavaScript, asynchronous operations utilize callbacks to further process the responses they receive from Web APIs.</p>
<p>The example below is an asynchronous operation with a callback function.</p>
<pre><code class="lang-javascript">button.addEventListener(<span class="hljs-string">'click'</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 was clicked!'</span>)
})
</code></pre>
<p>Now whenever the user clicks on the button, it triggers the callback function to fire. But the callback cannot happen unless the parent function calls or invokes it, which is dependent on the user's action.</p>
<p>You can also observe the use of callback functions with the <strong><code>fetch</code></strong> API.</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"&lt;https://jsonplaceholder.typicode.com/users&gt;"</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">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response))
</code></pre>
<p>In this example, the <strong><code>then</code></strong> method of the <strong><code>fetch</code></strong> object accepts an arrow function as an argument. The execution of this function is dependent on the response received from the fetch request, making it a callback function. </p>
<p>Also, in the second <strong><code>then</code></strong> method, you can see the usage of another callback. This is because the first callback returns another asynchronous function, necessitating the use of a callback.</p>
<p>To recap, a callback function is passed in as an argument to an asynchronous function and only runs when the asynchronous operation has been completed. This is similar to how Eich Agency only executes some tasks when their third-party vendors have called them back.</p>
<h3 id="heading-callback-queue">Callback Queue</h3>
<p>Continuing their examination of Eich Agency’s execution process, the Lerdorf Corp team also discovered that Eich Agency often received multiple “call-backs” from the vendors they contacted. Each of these responses needed some action from the Eich Agency team.</p>
<p>Eich Agency streamlined its process further by keeping a separate list. This was a list where, whenever a vendor sent them a response they were supposed to act on, they would put that action inside the list. </p>
<p>This is what they did for every “call-back” they got. Eich Agency eventually ended up with a queue of extra tasks to perform but in a list separate from the one up on their board.</p>
<p>That list is similar to the Callback Queue in the browser’s JavaScript Runtime. The callback queue is a software mechanism that stores callback functions to be run after the Web APIs have processed asynchronous functions. It uses the <a target="_blank" href="https://en.wikipedia.org/wiki/Queue_(abstract_data_type)">queue</a> data structure which works with the <strong>First In First Out (FIFO)</strong> approach. This means that the first callback added to that queue is going to be the first callback to leave.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/asynchronous-javascript---Page-2--4-.png" alt="JavaScript Runtime showing the Callback Queue" width="600" height="400" loading="lazy">
<em>JavaScript Runtime showing the Callback Queue</em></p>
<h3 id="heading-event-loops">Event Loops</h3>
<p>Eich Agency implemented one final step to make sure everything went well between them and their clients. They would wait until they completed the tasks on their initial board before addressing the queue of extra tasks.</p>
<p>Eich Agency designated a member of their core team to manage the queue of tasks. This team member would await the completion of the regular tasks by other team members. Once the initial tasks were cleared, the assigned team member would select the first item from the queue of extra tasks and display it on the board.</p>
<p>The core team would proceed to complete the assigned task, such as receiving the snack supplies from the vendors. Once accomplished, the team member responsible for managing the extra tasks would select the next item and add it to the board. The core team would then work towards achieving this task, and the process would repeat in a loop until all the items on the queue of extra tasks were exhausted.</p>
<p>The team member in charge of the extra tasks can be likened to the event loop in the browser’s JavaScript Runtime. The event loop is a loop that continuously checks if the call stack is empty. When the call stack is not empty, it allows the ongoing process to continue. But when the call stack becomes empty, the event loop fetches the task at the top of the callback queue and adds it to the call stack.</p>
<p>The event loop runs continuously as long as the program is running, always performing its function until the callback queue is completely empty. This is why the JavaScript Engine executes callbacks only after everything in the call stack has been processed.</p>
<p>For example, consider this code snippet.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A'</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">'B'</span>), <span class="hljs-number">0</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'C'</span>)

<span class="hljs-comment">// A</span>
<span class="hljs-comment">// C</span>
<span class="hljs-comment">// B</span>
</code></pre>
<p>It ends up logging A and C before B, even though the timeout was for 0 seconds. The reason for this is that the callback in <code>setTimeout</code> waited in the callback queue (<code>setTimeout</code> uses the Web API). The JavaScript Engine had to finish handling synchronous functions before handling the asynchronous ones. It needed the help of the event loop to send the callback function to the call stack.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/asynchronous-javascript---Page-2--5-.png" alt="The Event Loop in the JavaScript Runtime" width="600" height="400" loading="lazy">
<em>The Event Loop in the JavaScript Runtime</em></p>
<p>To complete the story, after Lerdorf Corp understood how Eich Agency operated, they were impressed. They admired the way Eich Agency utilized its resources, but they immediately saw that it posed a threat to them and could potentially impact their business negatively.</p>
<p>Later on though, Lerdorf Corp realized that their client base differed from that of Eich Agency. While Eich Agency excelled in planning social events, Lerdorf Corp specialized in working with companies and organizing corporate events. There was no need for them to feel threatened by Eich Agency’s success. :)</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you have learned various important concepts that illustrate the asynchronous nature of JavaScript. </p>
<p>We began by discussing the three fundamental characteristics of JavaScript – that it's single-threaded, that it's non-blocking, and that it's asynchronous – and acknowledged that they may initially appear contradictory. After that, we clarified this apparent misconception by explaining the details.</p>
<p>You learned some concepts like the JavaScript engine in the browser, the call stack, callbacks, the callback queue, and the event loop.</p>
<p>Additionally, we used a story as an analogy to enhance your understanding of these concepts further. With this, you should have gained a solid understanding of how asynchronous operations function in the browser.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Asynchronous JavaScript Works ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, you'll learn all about Asynchronous JavaScript. But before we dive into that, we need to make sure you understand what Synchronous code is and how it works. What is Synchronous Code? When we write a program in JavaScript, it execute... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-javascript/</link>
                <guid isPermaLink="false">66d45f6347a8245f78752a74</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Fri, 17 Feb 2023 18:37:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-zhang-kaiyv-1168940.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, you'll learn all about Asynchronous JavaScript.</p>
<p>But before we dive into that, we need to make sure you understand what Synchronous code is and how it works.</p>
<h2 id="heading-what-is-synchronous-code">What is Synchronous Code?</h2>
<p>When we write a program in JavaScript, it executes line by line. When a line is completely executed, then and then only does the code move forward to execute the next line.</p>
<p>Let's look at an example of this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> greet_one = <span class="hljs-string">"Hello"</span>
<span class="hljs-keyword">let</span> greet_two = <span class="hljs-string">"World!!!"</span>
<span class="hljs-built_in">console</span>.log(greet_one)
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>;i&lt;<span class="hljs-number">1000000000</span>;i++){
}
<span class="hljs-built_in">console</span>.log(greet_two);
</code></pre>
<p>Now if you run the above example on your machine you will notice that <code>greet_one</code> logs first. Then the program waits for a couple of seconds and then logs <code>greet_two</code>. This is because the code executes line by line. This is called synchronous code.</p>
<p>This creates lot of problems. For example, if a certain piece of code takes 10 seconds to execute, the code after it won't be able to execute until it's finished, causing delays.</p>
<h2 id="heading-what-is-asynchronous-code">What is Asynchronous Code?</h2>
<p>With asynchronous code, multiple tasks can execute at the same time while tasks in the background finish. This is what we call non-blocking code. The execution of other code won't stop while an asynchronous task finishes its work.</p>
<p>Let's see an example of asynchronous code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> greet_one = <span class="hljs-string">"Hello"</span>
<span class="hljs-keyword">let</span> greet_two = <span class="hljs-string">"World!!!"</span>
<span class="hljs-built_in">console</span>.log(greet_one)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Asynchronous"</span>);
}, <span class="hljs-number">10000</span>)
<span class="hljs-built_in">console</span>.log(greet_two);
</code></pre>
<p>In the above example, if you run the code on your machine you will see <code>greet_one</code> and <code>greet_two</code> logged even there is code in between those 2 logs.</p>
<p>Now, setTimeout is asynchronous so it runs in background, allowing code after it to execute while it runs. After 10 seconds, <code>Asynchronous</code> will print because we set a time of 10 seconds in setTimeout to execute it after 10 seconds.</p>
<p>In this tutorial, we will study asynchronous JavaScript in detail so you can learn how to write your own asynchronous code. I just wanted to give you a taste of async JavaScript using in-built functions to whet your appetite.</p>
<h1 id="heading-how-callbacks-work-in-javascript">How Callbacks Work in JavaScript</h1>
<blockquote>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">"A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action."</a> (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">MDN</a>)</p>
</blockquote>
<p>Let's look at a code example to see why using callbacks instead would be helpful:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">compute</span>(<span class="hljs-params">action, x, y</span>)</span>{
    <span class="hljs-keyword">if</span>(action === <span class="hljs-string">"add"</span>){
        <span class="hljs-keyword">return</span> x+y
    }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(action === <span class="hljs-string">"divide"</span>){
        <span class="hljs-keyword">return</span> x/y
    }
}

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

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

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

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

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

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

}

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

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

}

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

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

}

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

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

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

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

})

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


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


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


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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

fetchJokeWithAsyncAwait()
</code></pre>
<p>Here we have a function that executes the fetch and logs the response. See that we start by using the <code>async</code> keyword when we declare the function. This is a requirement for all functions that use async-await.</p>
<p>Then we enclose our fetch call in a <code>try-catch</code> statement. This is required because with async-await we won't use the <code>.catch</code> method. But we still need to process possible errors.</p>
<p>We achieve this with the use of <code>try-catch</code>. If anything contained in the <code>try</code> statement returns an error, then the <code>catch</code> statement executes, obtaining the error as a parameter.</p>
<p>As you can see, we are assigning the result of the <code>fetch</code> call to a variable called <code>res</code>. And before the <code>fetch</code> we're using the <code>await</code> keyword.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.chucknorris.io/jokes/random'</span>)
</code></pre>
<p>This means that Javascript will wait for the promise to resolve before assigning its value to the variable. And any operations done on that variable, will only execute once its value has been assigned.</p>
<p>In the next line we're calling the <code>.json()</code> method on the <code>res</code> variable, and again using the <code>await</code> keyword before it so the promise result is then assigned to the <code>data</code> variable.</p>
<p>And lastly, we log our <code>data</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-62.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As mentioned, async-await is just syntactic sugar. It doesn't do anything differently than <code>.then</code> and <code>.catch</code> methods. It's just easier to write and read.</p>
<h1 id="heading-wrap-up">Wrap-up</h1>
<p>Well everyone, as always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/were-out-of-time-out-of-time.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous JavaScript – Callbacks, Promises, and Async/Await Explained ]]>
                </title>
                <description>
                    <![CDATA[ If you've been learning JavaScript for a while now, then you've probably heard the term "asynchronous" before. This is because JavaScript is an asynchronous language...but what does that really mean? In this article, I hope to show you that the conce... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-javascript-explained/</link>
                <guid isPermaLink="false">66d460893a8352b6c5a2aac5</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Njong Emy ]]>
                </dc:creator>
                <pubDate>Mon, 20 Jun 2022 20:10:50 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727436410214/26117e35-6f63-4788-9b97-3aa225527213.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've been learning JavaScript for a while now, then you've probably heard the term "asynchronous" before.</p>
<p>This is because JavaScript is an asynchronous language...but what does that really mean? In this article, I hope to show you that the concept is not as difficult as it sounds.</p>
<h1 id="heading-synchronous-vs-asynchronous">Synchronous vs Asynchronous</h1>
<p>Before we hop into the real deal, let's look at these two words – synchronous and asynchronous.</p>
<p>By default, JavaScript is a synchronous, single threaded programming language. This means that instructions can only run one after another, and not in parallel. Consider the little code snippet below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> sum = a + b;
<span class="hljs-built_in">console</span>.log(sum);
</code></pre>
<p>The above code is pretty simple – it sums two numbers and then logs the sum to the browser console. The interpreter executes these instructions one after another in that order until it is done.</p>
<p>But this method comes along with disadvantages. Say we wanted to fetch some large amount of data from a database and then display it on our interface. When the interpreter reaches the instruction that fetches this data, the rest of the code is blocked from executing until the data has been fetched and returned.</p>
<p>Now you might say that the data to be fetched isn't that large and it won't take any noticeable time. Imagine that you have to fetch data at multiple different points. This delay compounded doesn't sound like something users would want to come across.</p>
<p>Luckily for us, the problems with synchronous JavaScript were addressed by introducing asynchronous JavaScript.</p>
<p>Think of asynchronous code as code that can start now, and finish its execution later. When JavaScript is running asynchronously, the instructions are not necessarily executed one after the other as we saw before.</p>
<p>In order to properly implement this asynchronous behavior, there are a few different solutions developers has used over the years. Each solution improves upon the previous one, which makes the code more optimized and easier to understand in case it gets complex.</p>
<p>To further understand the asynchronous nature of JavaScript, we will go through callback functions, promises, and async and await.</p>
<h1 id="heading-what-are-callbacks-in-javascript">What are Callbacks in JavaScript?</h1>
<p>A callback is a function that is passed inside another function, and then called in that function to perform a task.</p>
<p>Confusing? Let's break it down by practically implementing it.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fired first'</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fired second'</span>);

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

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

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

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

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

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

console.log(3);
console.log(4);
</code></pre>
<p>In our browser console, the output of the above would look something like this:</p>
<pre><code class="lang-markdown">1
2
3
4
data returned by asyncFunc
</code></pre>
<p>You see that as we called <code>asyncFunc</code>, our code continued running until it was time for the function to return results.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>This article does not treat these concepts in great depth, but I hope it shows you what asynchronous JavaScript entails and a few things to look out for.</p>
<p>It is a very essential part of JavaScript, and this article only scratches the surface. Nonetheless, I hope this article helped to break down these concepts.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Simplify Asynchronous JavaScript using the Result-Error Pattern ]]>
                </title>
                <description>
                    <![CDATA[ By Ken Snyder Over the last 18 years of programming, I've had to deal with asynchronous behavior in virtually every project.  Since the adoption of async-await in JavaScript, we've learned that async-await makes a lot of code more pleasant and easier... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/simplify-asynchronous-javascript-using-the-result-error-pattern/</link>
                <guid isPermaLink="false">66d45f65ffe6b1f641b5f9f7</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 18 Jan 2022 22:08:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/locomotive-gfe169d971_1920-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ken Snyder</p>
<p>Over the last 18 years of programming, I've had to deal with asynchronous behavior in virtually every project. </p>
<p>Since the adoption of async-await in JavaScript, we've learned that async-await makes a lot of code more pleasant and easier to reason about.</p>
<p>Recently I noticed that when I work with a resource that needs to asynchronously connect and disconnect, I end up writing code like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// NOT MY FAVORITE PATTERN</span>
router.get(<span class="hljs-string">'/users/:id'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> Client();
  <span class="hljs-keyword">let</span> user;
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> client.connect();
    user = <span class="hljs-keyword">await</span> client.find(<span class="hljs-string">'users'</span>).where(<span class="hljs-string">'id'</span>, req.path.id);
  } <span class="hljs-keyword">catch</span>(error) {
    res.status(<span class="hljs-number">500</span>);
    user = { error };
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-keyword">await</span> client.close();
  }
  res.json(user);
});
</code></pre>
<p>It gets verbose because we have to use try/catch to handle errors.</p>
<p>Examples of such resources include databases, ElasticSearch, command lines, and ssh.</p>
<p>In those use cases, I've settled into a code pattern I'm calling the Result-Error Pattern.</p>
<p>Consider rewriting the code above like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// I LIKE THIS PATTERN BETTER</span>
router.get(<span class="hljs-string">'/users/:id'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> { <span class="hljs-attr">result</span>: user, error } = <span class="hljs-keyword">await</span> withDbClient(<span class="hljs-function"><span class="hljs-params">client</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> client.find(<span class="hljs-string">'users'</span>).where(<span class="hljs-string">'id'</span>, req.path.id);
  });
  <span class="hljs-keyword">if</span> (error) {
    res.status(<span class="hljs-number">500</span>);
  }
  res.json({ user, error });
});
</code></pre>
<p>Notice a few things:</p>
<ol>
<li>The database client gets created for us and our callback can just utilize it.</li>
<li>Instead of capturing errors in a try-catch block, we rely on <code>withDbClient</code> to return errors.</li>
<li>The result is always called <code>result</code> because our callback may return any kind of data.</li>
<li>We don't have to close the resource.</li>
</ol>
<p>So what does <code>withDbClient</code> do?</p>
<ol>
<li>It handles creating the resource, connecting and closing.</li>
<li>It handles try, catch, and finally.</li>
<li>It ensures that there will be no uncaught exceptions thrown from <code>withDbClient</code>.</li>
<li>It ensures that any exceptions thrown in the handler also get caught inside <code>withDbClient</code>.</li>
<li>It ensures that <code>{ result, error }</code> will always be returned.</li>
</ol>
<p>Here is an example implementation:</p>
<pre><code class="lang-js"><span class="hljs-comment">// EXAMPLE IMPLEMENTATION</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withDbClient</span>(<span class="hljs-params">handler</span>) </span>{
  <span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> DbClient();
  <span class="hljs-keyword">let</span> result = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">let</span> error = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> client.connect();
    result = <span class="hljs-keyword">await</span> handler(client);
  } <span class="hljs-keyword">catch</span> (e) {
    error = e;
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-keyword">await</span> client.close();
  }
  <span class="hljs-keyword">return</span> { result, error };
}
</code></pre>
<h2 id="heading-a-step-further">A step further</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/pexels-tom-fisk-1595104.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Photo by <a target="_blank" href="https://www.pexels.com/@tomfisk">Tom Fisk</a> from Pexels</em></p>
<p>What about a resource that does not need to be closed? Well the Result-Error Pattern can still be nice!</p>
<p>Consider the following use of <code>fetch</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// THIS IS NICE AND SHORT</span>
<span class="hljs-keyword">const</span> { data, error, response } = <span class="hljs-keyword">await</span> fetchJson(<span class="hljs-string">'/users/123'</span>);
</code></pre>
<p>Its implementation might be the following:</p>
<pre><code class="lang-js"><span class="hljs-comment">// EXAMPLE IMPLEMENTATION</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchJson</span>(<span class="hljs-params">...args</span>) </span>{
  <span class="hljs-keyword">let</span> data = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">let</span> error = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">let</span> response = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(...args);
    <span class="hljs-keyword">if</span> (response.ok) {
      <span class="hljs-keyword">try</span> {
        data = <span class="hljs-keyword">await</span> response.json();
      } <span class="hljs-keyword">catch</span> (e) {
        <span class="hljs-comment">// not json</span>
      }
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// note that statusText is always "" in HTTP2</span>
      error = <span class="hljs-string">`<span class="hljs-subst">${response.status}</span> <span class="hljs-subst">${response.statusText}</span>`</span>;
    }
  } <span class="hljs-keyword">catch</span>(e) {
    error = e;  
  }
  <span class="hljs-keyword">return</span> { data, error, response };
}
</code></pre>
<h2 id="heading-higher-level-use">Higher-level use</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/aerial-g3ccde9887_1920.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Photo by <a target="_blank" href="https://pixabay.com/users/16018388-16018388/">16018388</a> from Pixabay</em></p>
<p>We don't have to stop at low-level use. What about other functions that may end with a result or error?</p>
<p>Recently, I wrote an app with a lot of ElasticSearch interactions. I decided to also use the Result-Error pattern on higher-level functions.</p>
<p>For instance, searching for posts produces an array of ElasticSearch documents and returns result and error like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { result, error, details } = <span class="hljs-keyword">await</span> findPosts(query);
</code></pre>
<p>If you've worked with ElasticSearch, you'll know that responses are verbose and data is nested several layers inside the response. Here, <code>result</code> is an object containing:</p>
<ol>
<li><code>records</code> – An Array of documents</li>
<li><code>total</code> – The total number of documents if a limit was not applied</li>
<li><code>aggregations</code> – ElasticSearch faceted-search information</li>
</ol>
<p>As you might guess, <code>error</code> may be an error message and <code>details</code> is the full ElasticSearch response in case you need things like error metadata, highlights, or query time.</p>
<p>My implementation for searching ElasticSearch with a query object reads something like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Fetch from the given index name with the given query</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">query</span>(<span class="hljs-params">index, query</span>) </span>{
  <span class="hljs-comment">// Our Result-Error Pattern at the low level  </span>
  <span class="hljs-keyword">const</span> { result, error } = <span class="hljs-keyword">await</span> withEsClient(<span class="hljs-function"><span class="hljs-params">client</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> client.search({
      index,
      <span class="hljs-attr">body</span>: query.getQuery(),
    });
  });
  <span class="hljs-comment">// Returning a similar object also with result-error</span>
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">result</span>: formatRecords(result),
    error,
    <span class="hljs-attr">details</span>: result || error?.meta,
  };
}

<span class="hljs-comment">// Extract records from responses </span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatRecords</span>(<span class="hljs-params">result</span>) </span>{
  <span class="hljs-comment">// Notice how deep ElasticSearch buries results?</span>
  <span class="hljs-keyword">if</span> (result?.body?.hits?.hits) {
    <span class="hljs-keyword">const</span> records = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> hit <span class="hljs-keyword">of</span> result.body.hits.hits) {
      records.push(hit._source);
    }
    <span class="hljs-keyword">return</span> {
      records,
      <span class="hljs-attr">total</span>: result.body.hits.total?.value || <span class="hljs-number">0</span>,
      <span class="hljs-attr">aggregations</span>: result.aggregations,
    };
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">records</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-literal">null</span>, <span class="hljs-attr">aggregations</span>: <span class="hljs-literal">null</span> };
  }
}
</code></pre>
<p>And then the <code>findPosts</code> function becomes something simple like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findPosts</span>(<span class="hljs-params">query</span>) </span>{
  <span class="hljs-keyword">return</span> query(<span class="hljs-string">'posts'</span>, query);
}
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>Here are the key aspects of a function that implements the Result-Error Pattern:</p>
<ol>
<li>Never throw exceptions.</li>
<li>Always return an object with the results and the error, where one may be null.</li>
<li>Hide away any asynchronous resource creation or cleanup.</li>
</ol>
<p>And here are the corresponding benefits of calling functions that implement the Result-Error Pattern:</p>
<ol>
<li>You don't need to use try-catch blocks.</li>
<li>Handling error cases is as simple as <code>if (error)</code>.</li>
<li>You don't need to worry about setup or cleanup operations.</li>
</ol>
<p>Don't take my word for it, try it yourself!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Handle Async Callbacks in JavaScript...Without Callbacks? ]]>
                </title>
                <description>
                    <![CDATA[ By Tobias Parent Noodling about on Discord today, the same question came up a few times on a few different servers. I thought it was a great question, and it seems my brain doesn't work quite the way others might expect.  Here's the question: "So I ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-handle-async-callbacks-in-javascript/</link>
                <guid isPermaLink="false">66d4614973634435aafcefda</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 04 Jan 2022 23:38:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/museums-victoria-TVe0IEdsVc8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Tobias Parent</p>
<p>Noodling about on Discord today, the same question came up a few times on a few different servers. I thought it was a great question, and it seems my brain doesn't work quite the way others might expect. </p>
<p>Here's the question:</p>
<blockquote>
<p>"So I have a <code>fetch</code> function, and I'm doing some <code>then</code> along with it to parse out the JSON data. I want to return that, but how can I? We can't <code>return</code> something from an asynchronous function call!"</p>
</blockquote>
<p>That's a great question. There's a lot going on there. We have ways of handling this within React, quite easily: we can <code>useState</code> to create some stateful variable, we can run our <code>fetch</code> within a <code>useEffect</code> and load that stateful variable, and we can use <em>another</em> <code>useEffect</code> to listen for that stateful variable to change. When the change happens, we can trigger our custom function and do some sort of side-effect with it.</p>
<p>With pure JavaScript, HTML, and CSS, it becomes a tad bit more tricky. For those who like to read the last page of the mystery novel before the rest, <a target="_blank" href="https://replit.com/@TobiasParent/HandlingLateLoadEvents#script.js">this replit</a> is where we'll end up.</p>
<h2 id="heading-an-ugly-beginning">An Ugly Beginning</h2>
<p>Suppose we want to fetch some todos from a server, and when we've loaded them we want to update the DOM. We might need to reload them, or append to them later – we want things to happen if our asynchronous functions do some sort of update to our <em>state</em>.</p>
<p>And yet, I don't really know how I feel about that. When we have a block of code like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> load = <span class="hljs-function">() =&gt;</span> {
  fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>)
    .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
    .then(<span class="hljs-function"><span class="hljs-params">jsonObj</span> =&gt;</span> {
      <span class="hljs-keyword">const</span> todoContainer = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".todos-container"</span>);
      <span class="hljs-comment">// now, take each todo, create its DOM, and poke it in.</span>
      jsonObj.forEach( <span class="hljs-function">(<span class="hljs-params">todo</span>)=&gt;</span>{
        <span class="hljs-keyword">const</span> todoEl = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>);
        todoEl.classList.add(<span class="hljs-string">"todo"</span>);
        <span class="hljs-keyword">const</span> todoTitle = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"h3"</span>);
        todoTitle.classList.add(<span class="hljs-string">"todo-title"</span>);
        todoTitle.textContent=todo.title;

        <span class="hljs-keyword">const</span> todoStatus = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>);
        todoStatus.classList.add(<span class="hljs-string">"todo-status"</span>);
        todoStatus.textContent = todo.done ? <span class="hljs-string">"Complete"</span> : <span class="hljs-string">"Incomplete"</span>;

        todoEl.append(todoTitle, todoStatus);
        todoContainer.append(todoEl)
    })
}
</code></pre>
<p>We kind of <em>have</em> to fill the DOM right there in the <code>.then()</code> block, because we can't really say "hey, when this is done, fire off this function." </p>
<p>We could simply await each of the Promises, rather than chaining them like this, and simply return the result of the final parsing:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> load = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>)
  <span class="hljs-keyword">const</span> jsonObj = <span class="hljs-keyword">await</span> result.json();
  <span class="hljs-keyword">const</span> todoContainer = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".todos-container"</span>);

  jsonObj.forEach( <span class="hljs-function">(<span class="hljs-params">todo</span>)=&gt;</span>{
    <span class="hljs-keyword">const</span> todoEl = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>);
    todoEl.classList.add(<span class="hljs-string">"todo"</span>);
    <span class="hljs-keyword">const</span> todoTitle = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"h3"</span>);
    todoTitle.classList.add(<span class="hljs-string">"todo-title"</span>);
    todoTitle.textContent=todo.title;

    <span class="hljs-keyword">const</span> todoStatus = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>);
    todoStatus.classList.add(<span class="hljs-string">"todo-status"</span>);
    todoStatus.textContent = todo.done ? <span class="hljs-string">"Complete"</span> : <span class="hljs-string">"Incomplete"</span>;

    todoEl.append(todoTitle, todoStatus);
    todoContainer.append(todoEl)
  })
  <span class="hljs-comment">// here, if we wanted, we could even return that object:</span>
  <span class="hljs-keyword">return</span> jsonObj;
}

<span class="hljs-comment">// later, we can do this:</span>
<span class="hljs-keyword">const</span> todos = <span class="hljs-keyword">await</span> load();
<span class="hljs-comment">// fills the DOM and assigns all the todos to that variable</span>
</code></pre>
<p>Now that is better, our <code>load()</code> function can be used to not only put those elements into the DOM, but it returns the data to us. </p>
<p>This is still not ideal, though – we are still having to fill that DOM when the result is loading, and we still have to wait for the loading to happen. We have no idea <em>when</em> <code>todos</code> is going to be something. Eventually, it will be, but we don't know when.</p>
<h2 id="heading-callbacks-anyone">Callbacks, Anyone?</h2>
<p>We do have the option of a callback function. It might be useful, instead of actually hard-coding the DOM construction stuff, to pass that off to something else. It makes the <code>load</code> function more abstract, as it isn't wired to a particular endpoint.</p>
<p>Let's see what that might look like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> load = <span class="hljs-keyword">async</span> (apiEndpoint, callbackFn) =&gt; {
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> fetch(apiEndpoint);
  <span class="hljs-keyword">if</span>(!result.ok){
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`An error occurred: <span class="hljs-subst">${result.status}</span>`</span>)
  }
  <span class="hljs-comment">// at this point, we have a good result:</span>
  <span class="hljs-keyword">const</span> jsonObj = <span class="hljs-keyword">await</span> result.json();
  <span class="hljs-comment">// run our callback function, passing in that object</span>
  callbackFn(jsonObj)
}

<span class="hljs-comment">// Let's use that. First, we'll make a callback function:</span>
<span class="hljs-keyword">const</span> todoHandler = <span class="hljs-function">(<span class="hljs-params">todos</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> todoContainer = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".todos-container"</span>);

  todos.forEach( <span class="hljs-function">(<span class="hljs-params">todo</span>)=&gt;</span>{
    <span class="hljs-keyword">const</span> todoEl = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>);
    todoEl.classList.add(<span class="hljs-string">"todo"</span>);
    <span class="hljs-keyword">const</span> todoTitle = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"h3"</span>);
    todoTitle.classList.add(<span class="hljs-string">"todo-title"</span>);
    todoTitle.textContent=todo.title;

    <span class="hljs-keyword">const</span> todoStatus = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>);
    todoStatus.classList.add(<span class="hljs-string">"todo-status"</span>);
    todoStatus.textContent = todo.done ? <span class="hljs-string">"Complete"</span> : <span class="hljs-string">"Incomplete"</span>;

    todoEl.append(todoTitle, todoStatus);
    todoContainer.append(todoEl)
  })    
}

load(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>, todoHandler);
</code></pre>
<p>That's nicer – we are now telling <code>load</code> what to load, and what to do when that fetch has completed. It works. And there isn't anything really <em>wrong</em> with that. Still, it has some drawbacks. </p>
<p>My callback is by no means complete. We aren't handling errors, we aren't really <em>gaining</em> anything by this approach. We don't get the data out of the <code>load</code> function in any sense we can use, in a timely fashion.</p>
<p>And again, me being me, I wanted to try a different way.</p>
<h2 id="heading-callbacks-without-callbacks">Callbacks Without Callbacks</h2>
<p>Okay, that <em>is</em> a little misleading. They're not callbacks. We are going to completely avoid <em>having</em> callbacks at all. What will we have instead? Event listeners!</p>
<p>The DOM is all about communication. Events fire off all over the place – mouse events, keyboard events, gestures and media and window... The browser is a noisy place. </p>
<p>But it is all <em>controlled</em>, it is all <em>intent-ful</em> and it is all <em>well-formed</em>. Things are encapsulated nicely, completely self-contained, but they can communicate events up and down the DOM tree as needed. And we can leverage that, with the <code>CustomEvent</code> API.</p>
<p>Creating a <code>CustomEvent</code> is not really that difficult, simply provide the name of the event as a string, and the <em>payload</em> – the information to be included in that event. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myShoutEvent = <span class="hljs-keyword">new</span> CustomEvent(<span class="hljs-string">'shout'</span>, {
  <span class="hljs-attr">detail</span>: {
    <span class="hljs-attr">message</span>: <span class="hljs-string">'HELLO WORLD!!'</span>,
    <span class="hljs-attr">timeSent</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>() 
  }
})

<span class="hljs-comment">// and later on, we can send that event:</span>
someDomEl.dispatchEvent(myShoutEvent);
</code></pre>
<p>That's all there is to a custom event. We create the event, including custom <code>detail</code> data, and then we <code>dispatchEvent</code> on a given DOM node. When that event is fired on that DOM node, it joins the normal stream of communication, riding along on the bubbling and capturing phases just like any normal event – because it <em>is</em> a normal event.</p>
<h2 id="heading-how-does-this-help-us">How does this help us?</h2>
<p>What if we were to <em>listen</em> for that custom event somewhere, and place the responsibility for handling that event (and its <code>detail</code>) with the receiver, rather than telling the <code>load</code> function what to do when we get that data?</p>
<p>With this approach, we don't really care <em>when</em> the fetch completes its processing, we don't care about some returning value in some global variable – we simply tell the DOM node to dispatch an event... <em>and pass along the fetched data as <code>detail</code></em>.</p>
<p>Let's start playing with this idea:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> load = <span class="hljs-function">(<span class="hljs-params">apiEndpoint, elementToNotify, eventTitle</span>) =&gt;</span> {
  fetch(apiEndpoint)
    .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> {
       <span class="hljs-comment">// here's where we do this: we want to create that custom event</span>
       <span class="hljs-keyword">const</span> customEvent = <span class="hljs-keyword">new</span> CustomEvent(eventTitle, {
         <span class="hljs-attr">detail</span>: {
           data
         }
       });
       <span class="hljs-comment">// now, we simply tell the element to do its thing:</span>
      elementToNotify.dispatchEvent(customEvent)
     })
};
</code></pre>
<p>That's it. That's the whole shebang. We load some endpoint, we parse it, we wrap the data in a custom event object, and we throw it out into the DOM. </p>
<p>The rest is outside of the concern of that <code>load</code> function. It doesn't <em>care</em> about what the data looks like, it doesn't <em>care</em> where it's coming from, it doesn't <em>return</em> anything. It does this one thing – fetch data and then yell about it.</p>
<p>Now, with that in place, how might we wire that in from the other side?</p>
<pre><code class="lang-js"><span class="hljs-comment">// a function to create the Todo element in the DOM...</span>
<span class="hljs-keyword">const</span> createTodo = <span class="hljs-function">(<span class="hljs-params">{id, title, completed}</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> todoEl = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>);
  todoEl.classList.add(<span class="hljs-string">"todo"</span>);

  <span class="hljs-keyword">const</span> todoTitle = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"h3"</span>);
  todoTitle.classList.add(<span class="hljs-string">"todo-title"</span>);
  todoTitle.textContent=todo.title;

  <span class="hljs-keyword">const</span> todoStatus = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>);
  todoStatus.classList.add(<span class="hljs-string">"todo-status"</span>);
  todoStatus.textContent = todo.done ? <span class="hljs-string">"Complete"</span> : <span class="hljs-string">"Incomplete"</span>;

  todoEl.append(todoTitle, todoStatus);

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

<span class="hljs-comment">// and when that load event gets fired, we want this to be</span>
<span class="hljs-comment">//  the event listener.</span>
<span class="hljs-keyword">const</span> handleLoad = <span class="hljs-function">(<span class="hljs-params">event</span>)=&gt;</span>{
  <span class="hljs-comment">// pull the data out of the custom event...</span>
  <span class="hljs-keyword">const</span> data = event.detail.data;
  <span class="hljs-comment">// and create a new todo for each object</span>
  data.forEach( <span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span> {
    event.target.append( createTodo(todo) )
  })
}

<span class="hljs-comment">// finally, we wire in our custom event!</span>
container.addEventListener(<span class="hljs-string">"todo.load"</span>, handleLoad)
</code></pre>
<p>That wires up the <code>container</code> to listen for that custom <code>todo.load</code> event. When the event happens, it fires off and executes that <code>handleLoad</code> listener. </p>
<p>It isn't doing anything particularly magic: it simply gets the <code>data</code> from that <code>event.detail</code> we create in the <code>load</code> function. Then the <code>handleLoad</code> calls the <code>createTodo</code> for each object in the <code>data</code>, creating our DOM node for each todo element.</p>
<p>Using this approach, we have nicely separated the data-fetching bits from the presentation bits. The only thing remaining is telling the one to talk to the other:</p>
<pre><code class="lang-js"><span class="hljs-comment">// remember, the parameters we defined were:</span>
<span class="hljs-comment">// apiEndpoint: url,</span>
<span class="hljs-comment">// elementToNotify: HTMLDomNode,</span>
<span class="hljs-comment">// eventTitle: string</span>
load(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>, container, <span class="hljs-string">'todo.load'</span>);
</code></pre>
<h2 id="heading-to-recap">To Recap</h2>
<p>We started with an ugly spaghetti-code mess – fetching logic mixed in with parsing and presentation. No good. I mean, we all do it, we use it all the time, but it just feels sketchy. There is no clean separation, and there is no way of working with the data outside of that <code>.then()</code>.</p>
<p>Using <code>async/await</code>, we <em>can</em> return that data, and we can use it outside the fetch if we need – but we have no real way of knowing when that data has been loaded. We can still process inline, loading the presentational layer in with the fetch, but that's no gain from the last.</p>
<p>Using callbacks, we can begin to separate – with a callback, we can load the data and, when the asynchronous operation is done, run the callback function. It does keep them nicely separated and it does pass the data into the callback as a parameter. It <em>is</em> better than mixing the presentation inline, but we <em>can</em> do something different.</p>
<p>And I mean that <em>different</em> – using the <code>CustomEvent</code> API is no better or worse than using callbacks. Both have their strengths and weaknesses. I like the clean-ness of the <code>CustomEvent</code> system, I like that we can extend that out. Some examples:</p>
<ul>
<li>a Timer class, that fires off a <code>"timer.tick"</code> and <code>"timer.complete"</code> event. The parent/container of that Timer's DOM node can listen for those events, <em>firing asynchronously</em>, and respond appropriately, whether updating the displayed time or causing a reaction when the timer's done.</li>
<li>our Todos – we could have the container listen for <code>"todo.load"</code>, <code>"todo.update"</code>, whatever custom events we like. We could handle updates by finding the relevant DOM node and updating its content, or removing all and replacing them on a load.</li>
</ul>
<p>We are separating the model logic from the presentation logic <em>entirely</em>, and defining an interface between the two. Clean, clear, reliable and simple.</p>
 ]]>
                </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[ Async and Await in JavaScript Explained by Making Pizza ]]>
                </title>
                <description>
                    <![CDATA[ By Dave Gray Async and await might sound complicated...but they're as easy as pizza pie once you dive in. We all use async and await in our daily routines. What is an async task? An async task lets you complete other tasks while the async task is sti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/async-await-javascript-tutorial-explained-by-making-pizza/</link>
                <guid isPermaLink="false">66d45e01a3a4f04fb2dd2e37</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 30 Aug 2021 20:20:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/carissa-gan-_0JpjeqtSyg-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dave Gray</p>
<p>Async and await might sound complicated...but they're as easy as pizza pie once you dive in.</p>
<p>We all use async and await in our daily routines.</p>
<h2 id="heading-what-is-an-async-task">What is an async task?</h2>
<p>An async task lets you complete other tasks while the async task is still working towards completion. </p>
<h3 id="heading-here-are-some-day-to-day-async-task-examples">Here are some day-to-day async task examples</h3>
<h4 id="heading-example-1">Example 1:</h4>
<p>You order food at a drive-thru which starts your food request (an async task). </p>
<p>You pull forward in the drive-thru line (the next task), while your food is prepared. </p>
<p>You did not have to wait for your food to be ready before you could pull forward.</p>
<p>You are awaiting your food and your request is fulfilled at the pick-up window.</p>
<h4 id="heading-example-2">Example 2:</h4>
<p>You mop the floor in your kitchen. </p>
<p>While you wait for your kitchen floor to dry, you vacuum the carpet in your bedroom. </p>
<p>The original task was to clean your kitchen floor, and the task is complete when the floor is dry. </p>
<p>Standing around waiting for the floor to dry is not too productive, so you vacuumed the bedroom floor while the kitchen floor dried.</p>
<p><em>This is how Javascript handles async functions, too.</em></p>
<h3 id="heading-example-of-asyncawait-bake-a-frozen-pizza">Example of Async/Await – Bake a Frozen Pizza</h3>
<p>You decide to bake a pizza in your oven, and your first step is to preheat the oven. </p>
<p>So you set the desired temperature and begin to preheat the oven. </p>
<p>While the oven is preheating, you get the frozen pizza out of the freezer, open the box, and put it on a pizza pan. </p>
<p>You've got time left! </p>
<p>Maybe grab a beverage and watch some television while you wait for the oven to beep when it is ready.</p>
<p>Below is some code to simulate this example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// This async function simulates the oven response</span>
<span class="hljs-keyword">const</span> ovenReady = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">'Beep! Oven preheated!'</span>)
  }, <span class="hljs-number">3000</span>));
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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