Asynchronous JavaScript: Everything you need to know
Tags: javascript, programming, webdev, beginners
Published: 2023-07-24 05:00:10

This article was written by Adeola Ajiboso

<header id="main-title" class="crayons-article__header">
<div class="crayons-article__header__meta">
<div class="spec__tags flex flex-wrap"><span style="font-size: 16px;">Asynchronous simply refers to making many events occur simultaneously in any order without waiting for one another, and this definition applies to asynchronous Javascript.</span></div>
</div>
</header>
<div class="crayons-article__main">
<div id="article-body" class="crayons-article__body text-styles spec__body" data-article-id="1536197">

​​
​​In this article, I'll go through the concept of asynchronous JavaScript, Callback, Promises, Async/Await, Callback queue, Event Loop, and Web browser features (Web API).
​​
​​Javascript is a single-threaded language that can only run one process at a time. JavaScript uses an event loop to carry out the operation, for now, consider the event loop as a queue where all Javascript processes are maintained and executed one at a time.
<blockquote>You should note Javascript is actually a Synchronous language. JavaScript executes lines of code sequentially, not concurrently, because it is by default, synchronous and single-threaded.</blockquote>
​​For instance, the code below will run and be executed line by line.
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="err">​​</span><span class="kd">let</span> <span class="nx">username</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">John</span><span class="dl">"</span><span class="p">;</span>
<span class="err">​​</span><span class="kd">let</span> <span class="nx">points</span> <span class="o">=</span> <span class="mi">5000</span><span class="p">;</span>
<span class="err">​​</span><span class="kd">let</span> <span class="nx">message</span> <span class="o">=</span> <span class="s2">`</span><span class="p">${</span><span class="nx">username</span><span class="p">}</span><span class="s2"> has earned </span><span class="p">${</span><span class="nx">points</span><span class="p">}</span><span class="s2"> points`</span><span class="p">;</span>
<span class="err">​​</span>
<span class="err">​​</span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">message</span><span class="p">);</span>
<span class="err">​​</span>
<span class="err">​​</span><span class="c1">//Output</span>
<span class="err">​​</span><span class="nx">John</span> <span class="nx">has</span> <span class="nx">earned</span> <span class="mi">5000</span> <span class="nx">points</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
The code above is executed synchronously, each line is completed before moving on to the next line.
​​
​​Let's consider a scenario where you need to retrieve a large amount of data from an API and display it. By default, in JavaScript, the execution is blocked, and all further instructions are halted until the retrieval request is completed. This is where asynchronous programming becomes crucial.
<div class="ff-container ff-ready ff-active"><button class="c-btn gif-button fs-s gap-2" type="button" aria-label="Pause animation playback" aria-pressed="false">GIF</button><canvas class="ff-canvas ff-canvas-ready" width="480" height="270"></canvas><img id="animated-0" class="ff-image" src="https://i.giphy.com/media/xT9IgLBsyBazb3SKmk/giphy.gif" width="480" height="270" data-animated="true" /></div>
​​Let’s dive in.
<h2><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#%E2%80%8B%E2%80%8Bwhat-is-asynchronous-javascript" name="%E2%80%8B%E2%80%8Bwhat-is-asynchronous-javascript"></a>​​What is Asynchronous JavaScript</h2>
​​Asynchronous JavaScript refers to the programming paradigm in which code execution does not follow the usual sequential flow from top to bottom. Instead, asynchronous code allows certain operations to be initiated and completed separately without blocking the execution of other code.
​​
​​The concept of asynchronous JavaScript enables you to break down big complex projects into smaller tasks.
<h1><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#what-is-involved-in-asynchronous-javascript" name="what-is-involved-in-asynchronous-javascript"></a>What is involved in Asynchronous JavaScript?</h1>
<ul>
 	<li>Web Browser features (Web API).</li>
 	<li>Callback queue.</li>
 	<li>Event loop.</li>
 	<li>Callback.</li>
 	<li>Async/Await.</li>
 	<li>Promise.</li>
</ul>
<h2><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#web-browser-features-web-api" name="web-browser-features-web-api"></a>Web Browser Features (Web API)</h2>
Browser APIs, also known as web APIs, are pre-existing interfaces embedded within web browsers. These APIs offer built-in functionalities that can be leveraged within web applications.

Web APIs allow developers to access and interact with these additional functionalities using JavaScript. By utilizing web APIs, developers can seamlessly incorporate specific features into their codebase while minimizing code complexity. Examples of such features include making network requests and efficiently managing client-side storage.

Some web browser features include:
<ul>
 	<li><code>setTimeout()</code></li>
</ul>
<blockquote>The <code>setTimeout()</code> method allows you to run a block of code after a certain time delay. It is designed to execute the code once.</blockquote>
The syntax of <code>setTimeout()</code> is:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span><span class="p">,</span> <span class="nx">milliseconds</span><span class="p">);</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Example:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">username</span><span class="p">()</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">John</span><span class="dl">"</span><span class="p">)</span>
<span class="p">}</span>

<span class="nx">setTimeout</span><span class="p">(</span><span class="nx">username</span><span class="p">,</span> <span class="mi">5000</span><span class="p">)</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Doe</span><span class="dl">"</span><span class="p">)</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Output:
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code>Doe
John
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
<ul>
 	<li><code>setInterval()</code></li>
</ul>
<blockquote>The <code>setInterval()</code> method repeats a block of code at every given timing event.</blockquote>
The syntax of <code>setInterval()</code> is :
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="nx">setInterval</span><span class="p">(</span><span class="kd">function</span><span class="p">,</span> <span class="nx">milliseconds</span><span class="p">);</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Example:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="c1">// program to display a text using setInterval method</span>
<span class="kd">function</span> <span class="nx">orderItem</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">I want a bag</span><span class="dl">'</span><span class="p">);</span>
<span class="p">}</span>

<span class="nx">setInterval</span><span class="p">(</span><span class="nx">orderItem</span><span class="p">,</span> <span class="mi">1000</span><span class="p">);</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Output:
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code>I want a bag
I want a bag
I want a bag
I want a bag
...
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
In the above program, the <code>orderItem()</code> function is invoked by the <code>setInterval()</code> method at an interval of 1000 milliseconds. Consequently, the program outputs the message "I want a bag" every 1 second.
<ul>
 	<li><code>clearTimeout()</code></li>
</ul>
<blockquote><code>clearTimeout()</code> method cancels a timeout previously established by calling <code>setTimeout()</code>.</blockquote>
The syntax of <code>clearTimeout()</code> is:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="nx">clearTimeout</span><span class="p">(</span><span class="nx">timeoutId</span><span class="p">)</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Example:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="c1">// Set a timeout that logs a message after 3 seconds</span>
<span class="kd">const</span> <span class="nx">timeoutId</span> <span class="o">=</span> <span class="nx">setTimeout</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Timeout executed!</span><span class="dl">"</span><span class="p">);</span>
<span class="p">},</span> <span class="mi">3000</span><span class="p">);</span>

<span class="c1">// Clear the timeout before it executes</span>
<span class="nx">clearTimeout</span><span class="p">(</span><span class="nx">timeoutId</span><span class="p">);</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Output:
If you run the code snippet provided, there will be no output. The <code>clearTimeout()</code> function cancels the execution of the timeout set by <code>setTimeout()</code> preventing the callback function from being invoked. As a result, the message “Timeout executed!" will not be logged to the console.
<ul>
 	<li><code>clearInterval()</code></li>
</ul>
<blockquote><code>clearInterval()</code> is used If you want to stop the function call.</blockquote>
The syntax of <code>clearInterval()</code> is:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="nx">clearInterval</span><span class="p">(</span><span class="nx">intervalId</span><span class="p">);</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Example:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="c1">// Define a variable to store the interval ID</span>
<span class="kd">let</span> <span class="nx">intervalId</span><span class="p">;</span>

<span class="c1">// Function to be executed repeatedly</span>
<span class="kd">function</span> <span class="nx">showMessage</span><span class="p">()</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Hello!</span><span class="dl">"</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">// Start the interval</span>
<span class="nx">intervalId</span> <span class="o">=</span> <span class="nx">setInterval</span><span class="p">(</span><span class="nx">showMessage</span><span class="p">,</span> <span class="mi">1000</span><span class="p">);</span>

<span class="c1">// After 5 seconds, stop the interval</span>
<span class="nx">setTimeout</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">clearInterval</span><span class="p">(</span><span class="nx">intervalId</span><span class="p">);</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Interval stopped</span><span class="dl">"</span><span class="p">);</span>
<span class="p">},</span> <span class="mi">5000</span><span class="p">);</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Output:
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code>Hello!
Hello!
Hello!
Hello!
Interval stopped
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
In the above program, you first declare a variable <code>intervalId</code> to store the ID returned by <code>setInterval</code> function. The <code>showMessage</code> function is defined, which will be executed repeatedly every 1000 milliseconds (1 second) using <code>setInterval</code>.
After 5 seconds (5000 milliseconds), <code>clearInterval</code> is called with the <code>intervalId</code> as the argument to stop the interval. This will stop the execution of the <code>showMessage</code> function. Finally, a message is logged to the console indicating that the interval has been stopped.
<ul>
 	<li><code>fetch()</code></li>
</ul>
<blockquote>The fetch() method in JavaScript is used to request data from a server.</blockquote>
They are not part of the JavaScript language, but they are built on top of the core JavaScript language, providing you with extra superpowers to use in your JavaScript code.

Read more about Web APIs 👉 <a href="https://developer.mozilla.org/en-US/docs/Web/API">here</a> 👈.
<h2><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#callback-queue" name="callback-queue"></a>Callback queue</h2>
The callback queue is where the callback function is pushed and awaits execution. The callback queue follows the First-In-First-Out(FIFO) principle.

Now let’s go through this example:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">username</span><span class="p">()</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">John</span><span class="dl">"</span><span class="p">)</span>
<span class="p">}</span>

<span class="nx">setTimeout</span><span class="p">(</span><span class="nx">username</span><span class="p">,</span> <span class="mi">5000</span><span class="p">)</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Doe</span><span class="dl">"</span><span class="p">)</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext"><code>//output
Doe
John
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
This block of code demonstrates the usage of the <code>setTimeout()</code> function to delay the execution of a callback function.

Here's how it works:
<ul>
 	<li>The <code>username</code> function is defined and stored in the Global memory, which logs the string "John" to the console.</li>
 	<li>The <code>setTimeout()</code> function is called with two arguments. The first argument is the <code>username</code> function, which specifies the callback function to be executed, and the second argument is the delay in milliseconds, which in this case is 5000 milliseconds (or 5 seconds).</li>
 	<li>After calling <code>setTimeout()</code>, the code continues to the next line and logs the string "Doe" to the console.</li>
 	<li>The string "Doe" is logged to the console first.</li>
 	<li>After the delay of 5000 milliseconds, the <code>username</code> function is executed and logs the string "John" to the console.</li>
</ul>
<h2><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#event-loop" name="event-loop"></a>Event Loop</h2>
The event loop continuously checks if the call stack is empty. If the call stack is empty, it means that there are no functions currently being executed. In that case, the loop takes the functions waiting in the callback queue and pushes them onto the call stack for execution. The event loop acts like a gatekeeper for the callback queue.

The event loop manages code execution to avoid blocking, enabling the program to proceed with its operation even during the completion of asynchronous tasks.
<h2><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#what-is-callback" name="what-is-callback"></a>What is Callback?</h2>
When you pass a function as an argument to another function, and that function is invoked or executed within the outer function, it is commonly referred to as a callback function.

<a class="article-body-image-wrapper" href="https://res.cloudinary.com/practicaldev/image/fetch/s--IItySWDh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/orf7rlcyy9mo7wyzz2cy.png"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IItySWDh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/orf7rlcyy9mo7wyzz2cy.png" alt="Callback Illustration" width="327" height="325" /></a>

Now let’s go through this example:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">placeOrder</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">setTimeout</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
       <span class="k">return</span> <span class="p">(</span><span class="nb">Math</span><span class="p">.</span><span class="nx">random</span><span class="p">()</span> <span class="o">*</span> <span class="mi">10</span><span class="p">)</span> <span class="o">&lt;=</span> <span class="mi">5</span> <span class="p">?</span> <span class="dl">'</span><span class="s1">Bag</span><span class="dl">'</span> <span class="p">:</span> <span class="dl">'</span><span class="s1">Shoe</span><span class="dl">'</span><span class="p">;</span>
    <span class="p">},</span> <span class="mi">2000</span><span class="p">);</span>
<span class="p">}</span>

<span class="kd">let</span> <span class="nx">order</span> <span class="o">=</span> <span class="nx">placeOrder</span><span class="p">();</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">Order is for: </span><span class="dl">'</span> <span class="o">+</span> <span class="nx">order</span><span class="p">);</span>

<span class="c1">//Output</span>
<span class="c1">// Order is for: undefined</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Here in the <code>placeOrder</code> function, the <code>setTimeout()</code> will run after 2 seconds, and by that time the <code>console.log</code> statement has already been executed, the printed value of <code>order</code> is undefined.

Now, you can resolve this issue by logging your message to the console only after the data has returned from <code>placeOrder</code>. This can be done by passing a callback function to <code>placeOrder</code>, which will be invoked inside the <code>placeOrder</code> function.
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">function</span> <span class="nx">placeOrder</span><span class="p">(</span><span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">setTimeout</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
        <span class="kd">const</span> <span class="nx">order</span> <span class="o">=</span> <span class="p">(</span><span class="nb">Math</span><span class="p">.</span><span class="nx">random</span><span class="p">()</span> <span class="o">*</span> <span class="mi">10</span><span class="p">)</span> <span class="o">&lt;=</span> <span class="mi">5</span> <span class="p">?</span> <span class="dl">'</span><span class="s1">Bag</span><span class="dl">'</span> <span class="p">:</span> <span class="dl">'</span><span class="s1">Shoe</span><span class="dl">'</span><span class="p">;</span>
        <span class="nx">callback</span><span class="p">(</span><span class="nx">order</span><span class="p">);</span>
    <span class="p">},</span> <span class="mi">2000</span><span class="p">);</span>
<span class="p">}</span>

<span class="nx">placeOrder</span><span class="p">((</span><span class="nx">order</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">Order is for: </span><span class="dl">'</span> <span class="o">+</span> <span class="nx">order</span><span class="p">);</span>
<span class="p">});</span>

<span class="c1">//Output</span>
<span class="c1">// Order is for: Bag</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
After two seconds, the callback function will be called, and the console statement will get executed with the correct order value.
<blockquote>The output of placeOrder function may differ in your case as you are using <code>Math.random()</code> to decide order value.</blockquote>
<h2><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#promise" name="promise"></a>Promise</h2>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> is an object in JavaScript that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Promises simplify handling asynchronous code, making it easier to write and maintain asynchronous operations without resorting to callback functions or nested callbacks (known as callback hell).
<blockquote>Callback hell is a term used to describe a situation where the code becomes hard to read and understand due to a large number of nested callback functions.</blockquote>
A promise can be in one of three states:
<ul>
 	<li>Pending: The initial state when a promise is created, and the asynchronous operation is still ongoing.</li>
 	<li>Fulfilled: The state when the asynchronous operation is successfully completed, and the promise has a resolved value.</li>
 	<li>Rejected: The state when the asynchronous operation encounters an error or fails, and the promise has a reason for rejection.</li>
</ul>
There are three main aspects of promises.
<ul>
 	<li>Creating a promise</li>
 	<li>Handling a promise</li>
 	<li>Chaining of promise</li>
</ul>
<h3><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#creating-promises" name="creating-promises"></a>Creating Promises</h3>
To create a promise, you use the Promise constructor, which accepts a function (commonly referred to as the executor) as an argument. The executor function is provided with two parameters: resolve and reject. Within the executor function, you execute your asynchronous task and invoke either resolve or reject based on the result.

Here's an example of creating a promise :
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="kd">const</span> <span class="nx">fetchData</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Promise</span><span class="p">((</span><span class="nx">resolve</span><span class="p">,</span> <span class="nx">reject</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="c1">// Simulating asynchronous task (e.g., making an API call)</span>
  <span class="nx">setTimeout</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="kd">const</span> <span class="nx">data</span> <span class="o">=</span> <span class="p">{</span> <span class="na">id</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">John Doe</span><span class="dl">"</span> <span class="p">};</span>
   <span class="c1">// Fulfilled the promise with the fetched data</span>
    <span class="nx">resolve</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span> 
    <span class="nx">reject</span><span class="p">(</span><span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="dl">"</span><span class="s2">Failed to fetch data</span><span class="dl">"</span><span class="p">));</span> 
    <span class="c1">// Alternatively, reject the promise with an error</span>
  <span class="p">},</span> <span class="mi">2000</span><span class="p">);</span>
<span class="p">});</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
<h3><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#handling-a-promise" name="handling-a-promise"></a>Handling a Promise</h3>
After creating a promise, you can assign callbacks to handle the result using the <code>then()</code> and <code>catch()</code> methods.

The <code>then()</code> method takes a callback function as an argument and manages the fulfilled promise. It receives the resolved value or result of the promise as an argument.

The <code>catch()</code> method is used to handle the rejection of a promise and it is called when the promise is rejected, allowing you to handle any errors that occurred during the asynchronous operation.

Now let's go through this example:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="nx">fetchData</span>
  <span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="c1">// Handle the fulfilled promise (access the resolved value)</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Fetched data:</span><span class="dl">"</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span>
  <span class="p">})</span>
  <span class="p">.</span><span class="k">catch</span><span class="p">((</span><span class="nx">error</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="c1">// Handle the rejected promise (access the error)</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Error:</span><span class="dl">"</span><span class="p">,</span> <span class="nx">error</span><span class="p">);</span>
  <span class="p">});</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
<h3><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#chaining-promises" name="chaining-promises"></a>Chaining Promises</h3>
Using the <code>then()</code> method, you can chain promises together to create a sequence of asynchronous operations. Each <code>then()</code> callback produces a new promise, enabling you to handle the outcome of the previous operation and proceed with the next one. Chaining promises allows you to establish a more sequential and readable flow of asynchronous operations.
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="nx">fetchData</span>
  <span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">data</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="c1">// Handle the first fulfilled promise</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Fetched data:</span><span class="dl">"</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span>
    <span class="k">return</span> <span class="nx">someOtherAsyncTask</span><span class="p">();</span> 
 <span class="c1">// Return a new promise</span>
  <span class="p">})</span>
  <span class="p">.</span><span class="nx">then</span><span class="p">((</span><span class="nx">result</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="c1">// Handle the result of the second fulfilled promise</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Second async task result:</span><span class="dl">"</span><span class="p">,</span> <span class="nx">result</span><span class="p">);</span>
  <span class="p">})</span>
  <span class="p">.</span><span class="k">catch</span><span class="p">((</span><span class="nx">error</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="c1">// Handle any errors in the chain</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Error:</span><span class="dl">"</span><span class="p">,</span> <span class="nx">error</span><span class="p">);</span>
  <span class="p">});</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
<h2><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#asyncawait" name="asyncawait"></a>Async/Await</h2>
Async/Await is a relatively recent addition to JavaScript, introduced in ES8, that provides a means to write asynchronous code in a synchronous manner.

If you use the <code>Async</code> keyword before the function definition, you can then use await within the function. <code>Await</code> gives you the power to pause the function in a non-blocking way until the promise is resolved.

Now let's go through this example:
<div class="highlight js-code-highlight">
<pre class="highlight javascript"><code><span class="k">async</span> <span class="kd">function</span> <span class="nx">fetchData</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">try</span> <span class="p">{</span>
    <span class="kd">const</span> <span class="nx">response</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">fetch</span><span class="p">(</span><span class="dl">'</span><span class="s1">https://jsonplaceholder.typicode.com/posts</span><span class="dl">'</span><span class="p">);</span>
    <span class="kd">const</span> <span class="nx">data</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">response</span><span class="p">.</span><span class="nx">json</span><span class="p">();</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">Fetched data:</span><span class="dl">'</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span>
  <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">Error fetching data:</span><span class="dl">'</span><span class="p">,</span> <span class="nx">error</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>
<span class="nx">fetchData</span><span class="p">();</span>
</code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action"></div>
</div>
</div>
Here’s the explanation to the code snippet:
<ul>
 	<li>An async function called <code>fetchUserData()</code> is declared. Inside this function, an asynchronous HTTP request is made to the API endpoint using the <code>fetch()</code> function. The <code>fetch()</code> function returns a promise that resolves to a response object.</li>
 	<li>The execution is paused using the <code>await</code> keyword, allowing the code to wait for the promise returned by <code>fetch()</code> to resolve. The resolved response object is stored in the <code>response</code> variable.</li>
 	<li>Another <code>await</code> keyword is used to pause the execution and wait for the promise returned by the <code>response.json()</code> method. This method parses the response body as JSON. The parsed JSON data is then stored in the <code>data</code> variable.</li>
 	<li>Finally, the fetched user data is logged to the console. If any errors occur during the execution of the async function, they are caught in the <code>catch</code> block, enabling the handling and logging of the errors.</li>
</ul>
<h1><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#conclusion" name="conclusion"></a>Conclusion</h1>
In this article, you’ve learned what asynchronous JavaScript is and how to write asynchronous JavaScript using promises and async/await. You’ve also seen how to send requests using the fetch API and async/await and how to return a response to asynchronous calls.
<blockquote>In JavaScript, synchronous instructions always take precedence over asynchronous instructions. For instance, if you have a scenario with numerous console.log statements followed by a setTimeout() function with a duration of 0 milliseconds, all the console.log statements will be executed first before the setTimeout().</blockquote>
I hope this article was informative? You can give it a like or comment on what you think.

<a class="crayons-link fw-bold" href="https://dev.to/comfortdeola">Adeola Ajiboso</a> is available on <a href="https://twitter.com/dde_olla">Twitter</a>, <a href="https://www.linkedin.com/in/adeola-ajiboso/">LinkedIn</a>, or <a href="https://github.com/Ajiboso-Adeola">GitHub</a>. Keep an eye out for my upcoming blog post, in which I'll go over another important area of web development. As a developer, I'm glad to provide additional information. Until then, happy coding, and take care!

If you find this post exciting, find more exciting posts on <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h1><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#resources" name="resources"></a>Resources</h1>
Here are some blogs/posts I read as a reference. You should check them out:
<ul>
 	<li><a href="https://dev.to/thanhtr99270163/asynchronous-javascript-js-demystified-3b8j">Asynchronous JavaScript (JS) Demystified</a> By <a href="https://dev.to/thanhtr99270163/asynchronous-javascript-js-demystified-3b8j">Thanh Truong's</a></li>
 	<li><a href="https://www.freecodecamp.org/news/javascript-async-await-tutorial-learn-callbacks-promises-async-await-by-making-icecream/">JavaScript Async/Await Tutorial – Learn Callbacks, Promises, and Async/Await in JS by Making Ice Cream 🍧🍨🍦</a> By <a href="https://www.freecodecamp.org/news/javascript-async-await-tutorial-learn-callbacks-promises-async-await-by-making-icecream/">Joy Shaheb</a></li>
</ul>
</div>
</div>