<?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[ callbacks - 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[ callbacks - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 20 May 2026 15:59:53 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/callbacks/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Callback Functions in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ When you're building dynamic applications with JavaScript that display real-time data – like a weather app or live sports dashboard – you'll need a way to automatically fetch new data from an external source without disrupting the user experience. Yo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-callback-functions-in-javascript/</link>
                <guid isPermaLink="false">66d4608fb6b7f664236cbe33</guid>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwadamisi Samuel ]]>
                </dc:creator>
                <pubDate>Wed, 03 Jul 2024 21:24:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/Callback_functions_JavaScript.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you're building dynamic applications with JavaScript that display real-time data – like a weather app or live sports dashboard – you'll need a way to automatically fetch new data from an external source without disrupting the user experience.</p>
<p>You can do this using JavaScript's callback functions, which showcase JavaScript's ability to handle asynchronous operations. Let's explore what callback functions are, how they work, and why they're essential in JavaScript.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-callback-function">What is a Callback function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-use-callback-functions">Why use Callback functions?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-basic-structure-of-a-callback-function">Basic Structure of a Callback Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-callbacks-work">How Callbacks Work</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-errors-with-callbacks">How to Handle Errors with Callbacks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-callback-hell-problem">The Callback Hell Problem</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-promises-and-asyncawait">How to Use Promises and Async/Await</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-a-callback-function">What is a Callback Function?</h2>
<p>A callback function is a function that is passed as an argument to another function and is executed after the completion of some operations.</p>
<p>This mechanism allows JavaScript to perform tasks like reading files, making HTTP requests, or waiting for user input without blocking the execution of the program. This helps ensure a smooth user experience.</p>
<h2 id="heading-why-use-callback-functions">Why Use Callback Functions?</h2>
<p>JavaScript runs in a single-threaded environment, meaning it can only execute one command at a time. Callback functions help manage asynchronous operations, ensuring that the code continues to run smoothly without waiting for tasks to complete. This approach is crucial for maintaining a responsive and efficient program.</p>
<h2 id="heading-basic-structure-of-a-callback-function">Basic Structure of a Callback Function</h2>
<p>To illustrate, let's look at a simple example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name, callback</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
  callback();
}

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

greet(<span class="hljs-string">"Alice"</span>, sayGoodbye);
</code></pre>
<p>In this code:</p>
<ul>
<li><p><code>greet</code> is a function that takes a name and a callback function as arguments.</p>
</li>
<li><p>After greeting the user, it calls the callback function.</p>
</li>
</ul>
<h2 id="heading-how-callbacks-work">How Callbacks Work</h2>
<ol>
<li><p><strong>Passing the Function:</strong> The function you want to run after some operation is passed as an argument to another function.</p>
</li>
<li><p><strong>Executing the Callback:</strong> The main function executes the callback function at the appropriate time. This can be after a delay, once a task is complete, or when an event occurs.</p>
</li>
</ol>
<p>Here’s a more detailed example with a simulated asynchronous operation using <code>setTimeout</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> data = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span> };
    callback(data);
  }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Simulating a delay of 2 seconds</span>
}

fetchData(<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 received:"</span>, data);
});
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>fetchData</code> simulates fetching data after a 2-second delay.</p>
</li>
<li><p>The callback function logs the data once it's received.</p>
</li>
</ul>
<h2 id="heading-how-to-handle-errors-with-callbacks">How to Handle Errors with Callbacks</h2>
<p>In real-world scenarios, you'll often need to handle errors. A common pattern is to pass an error as the first argument to the callback function:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">readFile</span>(<span class="hljs-params">filePath, callback</span>) </span>{
  <span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
  fs.readFile(filePath, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (err) {
      callback(err, <span class="hljs-literal">null</span>);
    } <span class="hljs-keyword">else</span> {
      callback(<span class="hljs-literal">null</span>, data);
    }
  });
}

readFile(<span class="hljs-string">'example.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error reading file:"</span>, err);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"File content:"</span>, data);
  }
});
</code></pre>
<p>Here:</p>
<ul>
<li><p>The <code>readFile</code> function reads a file asynchronously.</p>
</li>
<li><p>It calls the callback with an error (if any) or the file data.</p>
</li>
</ul>
<h2 id="heading-the-callback-hell-problem">The Callback Hell Problem</h2>
<p>As applications grow, using multiple nested callbacks can become complex and hard to manage, often referred to as "callback hell." Here’s an example of callback hell:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepOne</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> callback(<span class="hljs-literal">null</span>, <span class="hljs-string">'Step One Completed'</span>), <span class="hljs-number">1000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepTwo</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> callback(<span class="hljs-literal">null</span>, <span class="hljs-string">'Step Two Completed'</span>), <span class="hljs-number">1000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepThree</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> callback(<span class="hljs-literal">null</span>, <span class="hljs-string">'Step Three Completed'</span>), <span class="hljs-number">1000</span>);
}

stepOne(<span class="hljs-function">(<span class="hljs-params">err, result</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> <span class="hljs-built_in">console</span>.error(err);
  <span class="hljs-built_in">console</span>.log(result);
  stepTwo(<span class="hljs-function">(<span class="hljs-params">err, result</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> <span class="hljs-built_in">console</span>.error(err);
    <span class="hljs-built_in">console</span>.log(result);
    stepThree(<span class="hljs-function">(<span class="hljs-params">err, result</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> <span class="hljs-built_in">console</span>.error(err);
      <span class="hljs-built_in">console</span>.log(result);
    });
  });
});
</code></pre>
<p>This code is difficult to read and maintain. To solve this, modern JavaScript provides <code>Promises</code> and <code>async/await</code> syntax, making code cleaner and easier to handle.</p>
<h2 id="heading-how-to-use-promises-and-asyncawait">How to Use Promises and Async/Await</h2>
<p>Promises represent the eventual completion (or failure) of an asynchronous operation and its resulting value.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-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>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span> });
    }, <span class="hljs-number">2000</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 received:"</span>, data);
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error:"</span>, error);
  });
</code></pre>
<p>Async/Await syntax simplifies working with Promises:</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">getData</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 received:"</span>, data);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error:"</span>, error);
  }
}

getData();
</code></pre>
<p>This approach makes asynchronous code look and behave like synchronous code, improving readability and maintainability.</p>
<p>You can <a target="_blank" href="https://www.freecodecamp.org/news/guide-to-javascript-promises/">read more about promises and async/await here</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Callback functions are fundamental in JavaScript for handling asynchronous operations. While they offer a powerful way to manage asynchronous flow, they can become complex and hard to maintain.</p>
<p>Using Promises and async/await syntax can simplify your code, making it cleaner and easier to manage.</p>
<p>Understanding these concepts will help you write more efficient and maintainable JavaScript code.</p>
<p>Connect with me on <a target="_blank" href="http://www.linkedin.com/in/samuel-oluwadamisi-01b3a4236">LinkedIn</a> and <a target="_blank" href="https://twitter.com/Data_Steve_">Twitter</a> if you found this helpful.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous Programming in JavaScript – Callbacks, Promises, & Async/Await Examples ]]>
                </title>
                <description>
                    <![CDATA[ All programming languages have runtime engines that execute their code. In JavaScript, the runtime engine is single-threaded, which means that it runs code line by line or sequentially. The JavaScript runtime engine makes it a synchronous programming... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-programming-in-javascript-examples/</link>
                <guid isPermaLink="false">66d46042b3016bf139028d63</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Musab Habeeb ]]>
                </dc:creator>
                <pubDate>Fri, 02 Feb 2024 16:04:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Await-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>All programming languages have runtime engines that execute their code. In JavaScript, the runtime engine is single-threaded, which means that it runs code line by line or sequentially.</p>
<p>The JavaScript runtime engine makes it a synchronous programming language where programs run sequentially. Programming languages that are not synchronous are called asynchronous programming languages, which are programming languages where programs run concurrently.</p>
<p>Although JavaScript is synchronous, you can perform asynchronous programming with it. In this article, you will learn about asynchronous programming in JavaScript and how to use it.</p>
<h2 id="heading-what-is-asynchronous-programming">What is Asynchronous Programming?</h2>
<p>Asynchronous programming is a technique that allows your program to run its tasks concurrently. You can compare asynchronous programming to a chef with multiple cookers, pots, and kitchen utensils. This chef will be able to cook various dishes at a time.</p>
<p>Asynchronous programming makes your JavaScript programs run faster, and you can perform asynchronous programming with any of these:</p>
<ul>
<li><p>Callbacks</p>
</li>
<li><p>Promises</p>
</li>
<li><p>Async/Await</p>
</li>
</ul>
<p>In the upcoming sections, you will learn about these techniques and how to use them.</p>
<h2 id="heading-callbacks">Callbacks</h2>
<p>A callback is a function used as an argument in another function. Callbacks allow you to create asynchronous programs in JavaScript by passing the result of a function into another function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${name}</span>, how do you do?`</span>);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

greeting();
</code></pre>
<p>In the example above, the producing code is the <code>displayGreeting</code> function, and the consuming code is the <code>greet</code> function. The <code>greeting</code> function is the <code>Promise</code> that connects the producing and the consuming code. It waits for the result returned from the <code>displayGreeting</code> function and passes that result to the greet function.</p>
<h3 id="heading-error-handling-in-asyncawait">Error Handling in Async/Await</h3>
<p>You can easily handle errors that arise when you perform asynchronous operations with <code>async</code>/<code>await</code> using the <code>try...catch</code> statement. The asynchronous operation executes in the <code>try</code> block, and you can handle errors in the <code>catch</code> block.</p>
<p>That is:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">await</span> displayGreeting();
        greet(result);
    } <span class="hljs-keyword">catch</span>(err) {
        <span class="hljs-built_in">console</span>.error(err)
    }
};
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Asynchronous programming in JavaScript is used to make tasks in a program run concurrently and uses techniques such as callbacks, <code>Promise</code>, or <code>async</code>/<code>await</code>.</p>
<p>This article explains how to use these asynchronous programming techniques and how to handle errors with them.</p>
<p>You can check the <a target="_blank" href="https://javascript.info/async">promises and async/await section on the JavaScript.info website</a> to learn more about asynchronous programming in JavaScript.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Callbacks and Higher Order Functions in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ The way functions are treated and used in JavaScript is quite interesting. They are very flexible – we can assign functions as a value to a variable, return them as a value from another function, and pass them as an argument to another function. We c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/callbacks-higher-order-functions-in-javascript/</link>
                <guid isPermaLink="false">66ba596fbca875d7790d6a90</guid>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Franklin Okolie ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jan 2024 18:07:08 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/higher-order-callbacks.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The way functions are treated and used in JavaScript is quite interesting. They are very flexible – we can assign functions as a value to a variable, return them as a value from another function, and pass them as an argument to another function. We can do all this because JavaScript treats functions as <strong>first class citizens</strong>.</p>
<p>In this article, I'll go over what higher order functions and callbacks are, and how they work in JavaScript.</p>
<h2 id="heading-functions-as-first-class-citizens-in-javascript">Functions as First Class Citizens in JavaScript</h2>
<p>Functions are defined as <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function">first class citizens</a> or first class objects in JavaScript because functions are treated like variables.</p>
<p>This means that functions in JavaScript can be:</p>
<ul>
<li>Passed as an argument to a another function.</li>
<li>Assigned as a value to a variable.</li>
<li>Returned as a value from a function.</li>
</ul>
<p>It is essential to understand how functions are treated in JavaScript, as they serve as a building block to understanding higher order and callback functions in JavaScript and how they work.</p>
<h2 id="heading-what-are-higher-order-functions">What are Higher Order Functions?</h2>
<p>Higher order functions are functions that take functions as arguments and also return a function as a value. </p>
<p>There are a lot of built-in higher order functions provided in JavaScript. We'll take a look at some and take advantage of how functions are treated as first class citizens. We'll also create our own higher order functions.</p>
<p>First, let's take a look at some examples of built-in higher order functions.</p>
<h3 id="heading-array-methods">Array Methods</h3>
<p>Array methods are usually the first introduction of higher order functions a developer will have when learning JavaScript. These include, but are not limited to, the <code>map</code>, <code>filter</code>, <code>forEach</code>, <code>find</code>, <code>findIndex</code>, <code>some</code>, and <code>every</code> array methods provided by JavaScript.  </p>
<p>These array methods or functions have a lot in common, but one of the most common feature is that they all accept a function as an argument. Below is a code snippet that demonstrates how the <code>forEach</code> array method works:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> people = [
  { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Jack"</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1988</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Kait"</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1986</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Irv"</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">1970</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Lux"</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">2015</span> },
];

people.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">person</span>) </span>{
  <span class="hljs-built_in">console</span>.log(person);
});

<span class="hljs-comment">// Output:  Logs every person object in the array</span>
</code></pre>
<p>From the code sample above, we can see that the <code>forEach</code> method accepts a function as an argument which it calls on every iteration on the array. Therefore the <code>forEach</code> array method is a higher order function.</p>
<h3 id="heading-timer-events">Timer Events</h3>
<p>Another set of commonly used built-in higher order functions are the <code>setInterval</code> and <code>setTimeout</code> functions, known as timer events in JavaScript.</p>
<p>Each function accepts a function as one of its arguments and uses it to create a timed event.</p>
<p>Take a look at the code sample below to see how <code>setTimeout</code> works:</p>
<pre><code class="lang-javascript"><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">"This is a higher order function"</span>);
}, <span class="hljs-number">1000</span>);

<span class="hljs-comment">// Output: "This is a higher order function" after 1000ms / 1 second</span>
</code></pre>
<p>The code snippet above is the most basic example of how a <code>setTimeout</code> function works. It accepts a function and a time duration in milliseconds and executes the function after the provided duration has passed. </p>
<p>From the example above, <code>This is a higher order function</code> is printed to the console after 1000 ms, or one second.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setInterval</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">"This is a higher order function"</span>);
}, <span class="hljs-number">1000</span>);

<span class="hljs-comment">// Output: "This is a higher order function" after every 1000ms / 1 second</span>
</code></pre>
<p>The <code>setInterval</code> function is similar to the <code>setTimeout</code> function, just like the array methods – although it functions differently. But we can see a common pattern: it also accepts a function as one of its parameters.</p>
<p>Unlike <code>setTimeout</code> (that executes the function after the provided duration has passed), <code>setInterval</code> executes the function over and over again every 1000ms or 1 second.</p>
<h3 id="heading-how-to-create-and-use-a-higher-order-function">How to Create and Use a Higher Order Function</h3>
<p>Higher order functions are not limited to the built-in ones provided by JavaScript.</p>
<p>Since functions in JavaScript are treated as first class objects, we can take advantage of this behavior and build highly performant and reusable functions.</p>
<p>In the examples below, we'll build a couple of functions. They'll accept the name of a customer and a greeting, and then print that info to the console.</p>
<p>First, here is a simple function that does both of those things:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params">firstName, lastName, salutation</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">`<span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>`</span>;

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${salutation}</span> <span class="hljs-subst">${fullName}</span>`</span>);
}

greetCustomer(<span class="hljs-string">"Franklin"</span>, <span class="hljs-string">"Okolie"</span>, <span class="hljs-string">"Good Day"</span>);

<span class="hljs-comment">// Output: "Good Day Franklin Okolie"</span>
</code></pre>
<p><code>greetCustomer</code> accepts 3 arguments: a first name, a last name, and a salutation. Then it prints a greeting to the customer to the console.</p>
<p>But there is a problem with this function – it's doing two things: composing the full name of the customer and also printing the greeting.</p>
<p>This is not a best practice, as functions should do only one thing and do it well. So we are going to refactor our code.</p>
<p>Another function should compose the customer's name so that the <code>greetCustomer</code> function only has to print the greeting to the console. So let's write a function that handles that:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">composeName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">`<span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>`</span>;

  <span class="hljs-keyword">return</span> fullName;
}
</code></pre>
<p>Now that we have a function that combines the customer's first and last names, we can use that function in <code>greetCustomer</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params">composerFunc, firstName, lastName, salutation</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = composerFunc(firstName, lastName);

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${salutation}</span> <span class="hljs-subst">${fullName}</span>`</span>);
}

greetCustomer(composeName, <span class="hljs-string">"Franklin"</span>, <span class="hljs-string">"Okolie"</span>, <span class="hljs-string">"Good Day"</span>);

<span class="hljs-comment">// Output: "Good Day Franklin Okolie"</span>
</code></pre>
<p>Now this looks cleaner, and each function does just one thing. The <code>greetCustomer</code> function now accept 4 arguments, and since one of those arguments is a function, it's now a higher order function.</p>
<p>You might have wondered earlier, how is a function being invoked inside of another function, and why?</p>
<p>Now we'll take a deep dive into function invocation and answer both of those questions.</p>
<h3 id="heading-returning-a-function-as-a-value">Returning a Function as a Value</h3>
<p>Remember that higher order functions either take a function as a parameter and/or return a function as a value.</p>
<p>Let's refactor the <code>greetCustomer</code> function to use fewer arguments and return a function:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getGreetingsDetails</span>(<span class="hljs-params">composerFunc, salutation</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
    <span class="hljs-keyword">const</span> fullName = composerFunc(firstName, lastName);

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${salutation}</span> <span class="hljs-subst">${fullName}</span>`</span>);
  };
</code></pre>
<p>The last version of <code>greetCustomer</code> accepted too many arguments. Four arguments isn't a lot, but it would still be frustrating if you messed up the order of the arguments. Generally, the fewer arguments you have, the better.</p>
<p>So in the example above, we have a function called <code>getGreetingDetails</code> which accepts <code>composerFunc</code> and <code>salutation</code> on behalf of the inner <code>greetCustomer</code> function. It then returns the inner <code>greetCustomer</code> function, which itself accepts <code>firstName</code> and <code>lastName</code> as arguments.</p>
<p>By doing this, <code>greetCustomer</code> has fewer arguments overall.</p>
<p>And with that, let's take a look at how to use the <code>getGreetingDetails</code> function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greet = getGreetingsDetails(composeName, <span class="hljs-string">"Happy New Year!"</span>);

greet(<span class="hljs-string">"Quincy"</span>, <span class="hljs-string">"Larson"</span>);

<span class="hljs-comment">// Output: "Happy New Year Quincy Larson"</span>
</code></pre>
<p>Now take a step back and admire this beautiful abstraction. Marvelous! We have used the magic of higher order functions to simplify the <code>greetCustomer</code> function.</p>
<p>Let's walk through how everything works. The higher order function named <code>getGreetingDetails</code> takes in two arguments: a function to compose the customer's first and last name, and a salutation. Then it returns a function named <code>greetCustomer</code> which accepts the first and last name of a customer as arguments.</p>
<p> The returned <code>greetCustomer</code> function also uses the argument accepted by <code>getGreetingDetails</code> to execute some actions, too.</p>
<p>At this point you're probably wondering, how can a returned function use arguments provided to a parent function? Especially given how the function execution context works. It's possible because of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">closures</a>. Let's learn more about them now.</p>
<h3 id="heading-closures-explained">Closures Explained</h3>
<p>A closure is a function that has access to the variable in the scope where it was created even after the scope doesn't exist anymore in the execution context. This is one of the underlying mechanism of callbacks, as callbacks can still reference and use variables created in an outer function after that outer function has been closed.</p>
<p>Let's take a quick example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getTwoNumbers</span>(<span class="hljs-params">num1, num2</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> total = num1 + num2;
    <span class="hljs-built_in">console</span>.log(total);
  };
}

<span class="hljs-keyword">const</span> addNumbers = getTwoNumbers(<span class="hljs-number">5</span>, <span class="hljs-number">2</span>);

addNumbers();

<span class="hljs-comment">//Output: 7;</span>
</code></pre>
<p>The code in this example defines a function called <code>getTwoNumbers</code> and shows you how closures work. Let's explore it in more detail:</p>
<ol>
<li><code>getTwoNumbers</code> is defined as a function that takes two parameters, <code>num1</code> and <code>num2</code>.</li>
<li>Inside <code>getTwoNumbers</code>, it returns another function, which is an inner function named <code>add</code>.</li>
<li>The <code>add</code> function, when invoked, calculates the sum of <code>num1</code> and <code>num2</code> and logs the result to the console.</li>
<li>Outside the <code>getTwoNumbers</code> function, we create a variable called <code>addNumbers</code> and assign it the result of invoking <code>getTwoNumbers(5, 2)</code>. This effectively sets up a closure where <code>addNumbers</code> now "remembers" the values <code>5</code> and <code>2</code> as <code>num1</code> and <code>num2</code>.</li>
<li>Finally, we call <code>addNumbers()</code> to execute the inner <code>add</code> function. Since <code>addNumbers</code> is a closure, it still has access to the <code>num1</code> and <code>num2</code> values, which were set to <code>5</code> and <code>2</code>, respectively. It calculates their sum and logs <code>7</code> to the console.</li>
</ol>
<p>If you want to learn more about <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">closures, read more here</a>.</p>
<p>Back to our higher order function. The returned function <code>greetCustomer</code> gets returned as a value which we store in a variable named <code>greet</code>.</p>
<p>Doing that makes the <code>greet</code> variable itself a function, meaning we can invoke it as a function and pass in arguments for a first and last name.</p>
<p>And violà There you have it. These concepts can be a bit complex to grasp at first, but once you get the hang of them, they never leave you.</p>
<p>I encourage you to read through the previous sections again, play with the code in your editor, and to get the hang of how everything works together.</p>
<p>Now that you have an in-depth understanding about how higher order functions work, let's talk about callback functions.</p>
<h2 id="heading-what-are-callback-functions">What are Callback Functions?</h2>
<p>A callback function is a function that is passed into another function as an argument.</p>
<p>Again, one of the defining factors of functions as first class citizens is its ability to be passed as an argument to another function. This is called the <strong>act of passing callbacks</strong>.</p>
<p>Let go back and take a look at the timing events we discussed earlier when we were learning about the built-in functions provided in JavaScript. Here's the <code>setTimeout</code> function again:</p>
<pre><code class="lang-js"><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">"This is a higher order function"</span>);
}, <span class="hljs-number">1000</span>);

<span class="hljs-comment">// Output: "This is a higher order function" after 1000ms / 1 seconds</span>
</code></pre>
<p>We've established that the <code>setTimeout</code> function is a higher order function because it accepts another function as an argument.</p>
<p>The function that's passed as an argument to the <code>setTimeout</code> function is called a callback function. This is because it is invoked or executed inside of the higher order function it's passed into.</p>
<p>To get a better understanding of callback functions, let's take another look at the <code>greetCustomer</code> function from earlier:</p>
<pre><code class="lang-js"><span class="hljs-comment">// THIS IS A CALLBACK FUNCTION</span>
<span class="hljs-comment">// IT IS PASSED AS AN ARGUMENT TO A FUNCTION</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">composeName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">`<span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>`</span>;

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

<span class="hljs-comment">// THIS IS A HIGHER ORDER FUNCTION</span>
<span class="hljs-comment">// IT ACCPEPTS A FUNCTION AS A ARGUMENT</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params">composerFunc, firstName, lastName, salutation</span>) </span>{
  <span class="hljs-keyword">const</span> fullName = composerFunc(firstName, lastName);

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${salutation}</span> <span class="hljs-subst">${fullName}</span>`</span>);
}

greetCustomer(composeName, <span class="hljs-string">"Franklin"</span>, <span class="hljs-string">"Okolie"</span>, <span class="hljs-string">"Good Day"</span>);

<span class="hljs-comment">// Output: "Good Day Franklin Okolie"</span>
</code></pre>
<p>The <code>composeName</code> is a callback function that is passed as an argument into the <code>greetCustomer</code> function a higher order function and it is executed inside this function.</p>
<h2 id="heading-the-difference-between-higher-order-functions-and-callback-functions">The Difference Between Higher Order Functions and Callback Functions</h2>
<p>It's important that we understand the difference between these two terms so we can communicate more clearly with teammates and during technical interviews:</p>
<ul>
<li><strong>Higher Order Function</strong>: A function that accepts a function as an argument and/or returns a function as its value.</li>
<li><strong>Callback Function</strong>: A function that's passed as a argument to another function.</li>
</ul>
<h3 id="heading-a-bag-and-book">A Bag and Book</h3>
<p>To further understand these terms, I'll share a simple analogy.</p>
<p>Imagine you have a bag and a book. You carry the book in your bag while attending a meeting, going to class, going to church, and so on.</p>
<p>In this scenario, the bag accepts your book to carry it, and also returns it when you want to use it. So the bag is like a higher order function.</p>
<p>The book is kept inside of the bag until it's ready to be used, so it's like a callback function.</p>
<h3 id="heading-fuel-and-fuel-tank">Fuel and Fuel Tank</h3>
<p>Let's take a look at another analogy; fuel and a fuel tank.</p>
<p>To fuel a car, we have to pour the fuel through the fuel tank, the fuel tank recieves the fuel – just like a higher order function.</p>
<p>The fuel is poured into the fuel tank – like a callback function.</p>
<p>I hope these analogies help to further simplify higher order and callback functions and the difference between them.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As you can see, functions in JavaScript are very flexible, and can be used in a lot of helpful ways. This flexibility also lead to two common technical terms in JavaScript, higher order functions and callback functions.</p>
<p>If you want to learn more about these topics, check out the MDN documentation on functions as <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function">first class citizens</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function">higher order functions</a>, and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">callback functions</a>.</p>
<p>I hope you learned a lot from this article, and I hope you use your newfound knowledge to communicate your thoughts more clearly during pair coding sessions or during technical interviews.</p>
<p>For more JavaScripts tips, follow me on <a target="_blank" href="https://twitter.com/developeraspire">Twitter</a>.</p>
<p>Thanks for reading! See you next time.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Callbacks Work in Node.js ]]>
                </title>
                <description>
                    <![CDATA[ By Aditya Gupta Node.js callbacks are a special type of function passed as an argument to another function.  They're called when the function that contains the callback as an argument completes its execution, and allows the code in the callback to ru... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/nodejs-callbacks/</link>
                <guid isPermaLink="false">66d45d5dc17d4b8ace5b9eac</guid>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 28 Feb 2023 22:53:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-chepte--cormani-1416530.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Aditya Gupta</p>
<p>Node.js callbacks are a special type of function passed as an argument to another function. </p>
<p>They're called when the function that contains the callback as an argument completes its execution, and allows the code in the callback to run in the meantime.</p>
<p>Callbacks help us make asynchronous calls. Even Node.js APIs are written in a way that supports callbacks.</p>
<p><strong>Here's the syntax of a callback in Node:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">function_name</span>(<span class="hljs-params">argument, callback</span>)</span>
</code></pre>
<h2 id="heading-how-to-use-callbacks-in-node"><strong>How to Use Callbacks in Node</strong></h2>
<p>The callback is used to define what happens when the function containing the callback as an argument completes its execution.</p>
<p>For example, we can define a callback to print the error and result after the function execution.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">function_name</span>(<span class="hljs-params">argument, function (error, result){ if(error){ console.log(error) } else { console.log(result) } }</span>)</span>
</code></pre>
<h2 id="heading-how-to-write-callbacks"><strong>How to Write Callbacks</strong></h2>
<p>You can write a callback function in two ways: as an arrow function, and as a standard function without a name. Both ways will give you the same result.</p>
<h3 id="heading-how-to-write-a-callback-as-a-standard-function-without-a-name">How to write a callback as a standard function without a name</h3>
<p>You can write a callback as a regular function. You do that using a function keyword then the argument inside round brackets. Then you use curly brackets where you can define the callback body. It is not required to define the function name since it is automatically called.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">function_name</span>(<span class="hljs-params">argument, function (callback_argument){
    <span class="hljs-regexp">//</span> callback body 
}</span>)</span>
</code></pre>
<p>Let’s see an example of a callback using the setTimeout function. You can use this method to define a callback function that runs after a definite time.</p>
<pre><code class="lang-javascript"><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">'Callback as Standard Function'</span>); 
}, <span class="hljs-number">1000</span>);
</code></pre>
<p>Here we define a callback that runs after 1000 milliseconds which is equivalent to 1 second.</p>
<p><strong>Output:</strong></p>
<p><img src="https://codeforgeek.com/wp-content/uploads/2022/11/callback-standard.png" alt="Callback Standard" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-write-a-callback-as-an-arrow-function">How to write a callback as an arrow function</h3>
<p>It may be confusing to have multiple function keywords in a block of code. To eliminate the function keyword in the callback, you can use an arrow function. The arrow function was introduced in ES6 and helps you write cleaner code by removing the function keyword.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">function_name</span>(<span class="hljs-params">argument, (callback_argument) =&gt; { 
    <span class="hljs-regexp">//</span> callback body 
}</span>)</span>
</code></pre>
<p>Let’s rewrite the same example we wrote in the above section using an arrow function. Here we change the string to "Callback as Arrow Function".</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">'Callback as Arrow Function'</span>); 
}, <span class="hljs-number">1000</span>);
</code></pre>
<p><strong>Output:</strong></p>
<p><img src="https://codeforgeek.com/wp-content/uploads/2022/11/callback-as-arrow-function.png" alt="Callback As Arrow Function" width="600" height="400" loading="lazy"></p>
<h2 id="heading-asynchronous-programming-using-callbacks">Asynchronous Programming Using Callbacks</h2>
<p>Asynchronous programming is an approach to running multiple processes at a time without blocking the other part(s) of the code.</p>
<p>By using callbacks, we can write asynchronous code in a better way. For example, we can define a callback that prints the result after the parent function completes its execution. Then there is no need to block other blocks of the code in order to print the result.</p>
<p>Let’s take the example of a file system module which used to interact with files in Node.js. For reading a file, we can use the <code>readFileSync</code> method.</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>);

<span class="hljs-keyword">const</span> data = fs.readFileSync(<span class="hljs-string">'hello.txt'</span>, <span class="hljs-string">'utf-8'</span>); <span class="hljs-built_in">console</span>.log(data);
</code></pre>
<p><strong>Output:</strong></p>
<p><img src="https://codeforgeek.com/wp-content/uploads/2022/11/output-read-sync.png" alt="Output Read Sync" width="600" height="400" loading="lazy"></p>
<p>But this way our code holds up the execution of the rest of the program until it finishes its execution and prints the result. </p>
<p>Luckily, we can use a callback to write the code asynchronously without blocking the rest of the execution using the readFile method. When the reading of the file is done, then the callback gets triggered and prints the result.</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>); 

<span class="hljs-keyword">const</span> data = fs.readFile(<span class="hljs-string">'hello.txt'</span>, <span class="hljs-string">'utf-8'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, result</span>)</span>{ 
    <span class="hljs-keyword">if</span>(err){ 
        <span class="hljs-built_in">console</span>.log(err) 
    } <span class="hljs-keyword">else</span> { 
        <span class="hljs-built_in">console</span>.log(result) 
    } 
});
</code></pre>
<p><strong>Output:</strong></p>
<p><img src="https://codeforgeek.com/wp-content/uploads/2022/11/output-read-sync-1.png" alt="Output Read Async" width="600" height="400" loading="lazy"></p>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>NodeJS callbacks are a special type of function you can use to write asynchronous code. They give you a way to execute a block of code in the meantime after the execution of a function. You can define whether it prints a result, error, or performs the extra operation of the function result. </p>
<p>There are two ways to write a function: without a function name, or in the form of an arrow function. The arrow function is more convenient and results in cleaner code by removing the use of annoying function keywords. </p>
<p>I hope this article helps you understand Node.js callbacks.</p>
<p>You can <a target="_blank" href="https://nodejs.org/en/knowledge/getting-started/control-flow/what-are-callbacks/">have a look at the docs here</a> if you want to learn more.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Callback Function in JavaScript? JS Callbacks Example Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript there are higher order methods and functions that accept a function as an argument. These functions used as arguments for other functions are called callback functions. What is a callback in JavaScript? A callback is a function passed a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-callback-function-in-javascript-js-callbacks-example-tutorial/</link>
                <guid isPermaLink="false">66b0c3bcc82f8da076e5b028</guid>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ilenia Magoni ]]>
                </dc:creator>
                <pubDate>Tue, 09 Aug 2022 00:32:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/pexels-pixabay-39656.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript there are higher order methods and functions that accept a function as an argument. These functions used as arguments for other functions are called callback functions.</p>
<h2 id="heading-what-is-a-callback-in-javascript">What is a callback in JavaScript?</h2>
<p>A callback is a function passed as an argument of another function.</p>
<p>This means that the parent function is usually built to use any kind of function. But the callback function, on the other hand, is meant to be used in a specific case (or a restricted number of cases) in which the parent function is used. </p>
<h2 id="heading-how-do-you-create-a-callback-function-in-javascript">How do you create a callback function in JavaScript?</h2>
<p>You create a callback function just like any other function in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span> (<span class="hljs-params"></span>) </span>{

}
</code></pre>
<p>The difference between a callback function and any other function is how it's used.</p>
<p>A callback function is specifically built to be used as argument of another function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">anyFunction</span>(<span class="hljs-params">fun</span>) </span>{
    <span class="hljs-comment">// ...</span>
    fun(a, b, c);
    <span class="hljs-comment">//...</span>
}

anyFunction(callbackFunction);
</code></pre>
<p>So, to create a <code>callbackFunction</code> you need to know how the parent function uses the callback function, what arguments it passes in, and what order it passes them in.</p>
<h3 id="heading-what-is-an-example-of-a-callback-function">What is an example of a callback function?</h3>
<p>We'll now write our own callback function, as it's something you'll have to do many times. So, let's start!</p>
<p>A higher order function that's already integrated in the JavaScript language is the <code>every</code> method.</p>
<p>The <code>every</code> method is an array method, and uses a callback to check that all the elements in the array pass a certain test.</p>
<p>Looking at the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every">documentation on the <code>every</code> method</a>, you can see that the callback is passed three arguments: an element of the array, the index of that element, and the whole array.</p>
<p>So the callback function signature would be something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params">element, index, array</span>) </span>{
    <span class="hljs-comment">// do something</span>
}
</code></pre>
<p>Callback functions can be as simple or as complex as you need them to be. To create an example, we need some context.</p>
<h3 id="heading-how-to-write-a-callback-function-in-javascript">How to write a callback function in JavaScript</h3>
<p>So, let's say you are working with arrays of strings. You need to check if the array contains only strings that are exactly three characters long, are uppercase, contain all different letters, and that they don't repeat inside the array.</p>
<p>This is a pretty complex case, but maybe you will eventually need to do something like this or of equal complexity, so it's all good practice.</p>
<p>You can tackle one condition at a time when you build a function with so many things to check.</p>
<p>The first condition is that the element is a string, so, let's add it:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params">element, index, array</span>) </span>{

    <span class="hljs-comment">// check that element is a string</span>
    <span class="hljs-keyword">const</span> isNotString = <span class="hljs-keyword">typeof</span> element !== <span class="hljs-string">"string"</span>;
    <span class="hljs-comment">// if it's not, end function</span>
    <span class="hljs-keyword">if</span> (isNotString) {<span class="hljs-keyword">return</span>;}

}
</code></pre>
<p>Next, the strings must be all uppercase, contain only letters, and be 3 characters long.</p>
<p>You could check these three conditions separately, or you can check them together with a regular expression that checks for exactly those three things.</p>
<p>Such a regular expression would look like this: <code>/^[A-Z]{3}$/</code>.</p>
<p>Let's see what the parts of this regular expression are:</p>
<ul>
<li>The characters <code>^</code> at the beginning and <code>$</code> at the end are anchors. These say that the string must start and end in exactly that way. And if you use both, they restrict a string to contain only and exactly the pattern in the regular expression.</li>
<li><code>[A-Z]</code> is a character class that matches any character from <code>A</code> to <code>Z</code>, so all uppercase letters.</li>
<li><code>{3}</code> is a counter. This says that the previous thing must be matched exactly three consecutive times.</li>
</ul>
<p>The regular expression explained above is the equivalent of this regular expression: <code>/^[A-Z][A-Z][A-Z]$/</code>.</p>
<p>In this case instead of the counter <code>{3}</code> we have written the class <code>[A-Z]</code> three times.</p>
<p>Let's add this to the code.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params">element, index, array</span>) </span>{

    <span class="hljs-comment">// check that element is a string</span>
    <span class="hljs-keyword">const</span> isNotString = <span class="hljs-keyword">typeof</span> element !== <span class="hljs-string">"string"</span>;
    <span class="hljs-comment">// if it's not, end function</span>
    <span class="hljs-keyword">if</span> (isNotString) {
        <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-comment">// check that string is 3 characters long and only uppercase letters</span>
    <span class="hljs-keyword">const</span> isItThreeUpperCaseLetters = <span class="hljs-regexp">/^[A-Z]{3}$/</span>.test(element);
    <span class="hljs-comment">// otherwise, end function</span>
    <span class="hljs-keyword">if</span> (!isItThreeUpperCaseLetters) {
        <span class="hljs-keyword">return</span>;
    }

}
</code></pre>
<p>If you don't like regular expressions, you can read <a class="post-section-overview" href="#heading-and-if-we-didnt-use-a-regular-expression">below</a> how to do the same checks without using a regular expression.</p>
<p>Then, next, we need to check if the characters are all different.</p>
<p>There are three characters you can use: <code>element[0] !== element[1] &amp;&amp; element[0] !== element[2] &amp;&amp; element[1] !== element[2]</code>. </p>
<p>But, you can also do this with a loop – a double loop actually.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// with the outer loop, you get j, the first index to compare</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">0</span>; j++; j &lt; element.length) {
    <span class="hljs-comment">// with the inner loop you get k, the second index to compare</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> k = j+<span class="hljs-number">1</span>; k++; k &lt; element.length) {
        <span class="hljs-comment">// you compare the element at index j with the element at index k</span>
        <span class="hljs-keyword">if</span> (element[j] === element[k]) {
            <span class="hljs-comment">// if they are equal return to stop the function</span>
            <span class="hljs-keyword">return</span>;
        }
    }
}
</code></pre>
<p>The loop will work with any length, and you don't need to rewrite it for different situations.</p>
<p>Is it the exact same as writing the three comparisons? Let's follow the loop to check.</p>
<p>At first iteration we have that <code>j=0</code>, and <code>k=1</code>, so the first comparison is <code>element[0] === element[1]</code>. Then <code>k</code> increases, so it's <code>j=0</code> and <code>k=2</code>, so that is <code>element[0] === element[2]</code>.</p>
<p>At this point the inner loop stops, and the outer loop (the one with <code>j</code>) goes to the next iteration. This time <code>j=1</code>, and the inner loop starts at <code>k=j+1</code> so at <code>k=2</code> – the comparison here is <code>element[1] === element[2]</code>.</p>
<p>The inner loop has finished looping, the outer loop goes from <code>j=1</code> to <code>j=2</code>, the inner loop doesn't start as <code>k = j+1 = 3</code> doesn't pass the <code>k &lt; element.length</code> condition of the loop.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params">element, index, array</span>) </span>{


    <span class="hljs-comment">// check that element is a string</span>
    <span class="hljs-keyword">const</span> isNotString = <span class="hljs-keyword">typeof</span> element !== <span class="hljs-string">"string"</span>;
    <span class="hljs-comment">// if it's not, end function</span>
    <span class="hljs-keyword">if</span> (isNotString) {
        <span class="hljs-keyword">return</span>;
    }


    <span class="hljs-comment">// check that string is 3 characters long and only uppercase letters</span>
    <span class="hljs-keyword">const</span> isItThreeUpperCaseLetters = <span class="hljs-regexp">/^[A-Z]{3}$/</span>.test(element);
    <span class="hljs-comment">// otherwise, end function</span>
    <span class="hljs-keyword">if</span> (!isItThreeUpperCaseLetters) {
        <span class="hljs-keyword">return</span>;
    }


    <span class="hljs-comment">// check if all characters are different</span>
    <span class="hljs-keyword">const</span> allDifferentCharacters = element[<span class="hljs-number">0</span>] !== element[<span class="hljs-number">1</span>] &amp;&amp; element[<span class="hljs-number">0</span>] !== element[<span class="hljs-number">2</span>] &amp;&amp; element[<span class="hljs-number">1</span>] !== element[<span class="hljs-number">2</span>];
    <span class="hljs-comment">// if not, return to stop the function</span>
    <span class="hljs-keyword">if</span> (!allDifferentCharacters) {
        <span class="hljs-keyword">return</span>;
    }



}
</code></pre>
<p>Then, the last thing we need to check is that the strings are not repeated inside the array.</p>
<p>We can use <code>indexOf</code> to check that the current one is the first appearance of <code>element</code> inside the array.</p>
<p>We would need to reference the array for this. And we have it – it's one of the arguments passed in to the callback, the <code>array</code> parameter.</p>
<p>If this is the first appearance of the string in the array, the output of <code>indexOf</code> will be the same as <code>index</code>.</p>
<p>If  <code>array.indexOf(element) === index</code> is <code>true</code>, that means that <code>element</code> is present in the array for the first time at <code>index</code>. If it's <code>false</code>, an identical string is present earlier in the array.</p>
<p>Let's add this check to the function. And if the string has survived through all the checks, then the function can return <code>true</code> at the end.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params">element, index, array</span>) </span>{


    <span class="hljs-comment">// check that element is a string</span>
    <span class="hljs-keyword">const</span> isNotString = <span class="hljs-keyword">typeof</span> element !== <span class="hljs-string">"string"</span>;
    <span class="hljs-comment">// if it's not, end function</span>
    <span class="hljs-keyword">if</span> (isNotString) {
        <span class="hljs-keyword">return</span>;
    }


    <span class="hljs-comment">// check that string is 3 characters long and only uppercase letters</span>
    <span class="hljs-keyword">const</span> isItThreeUpperCaseLetters = <span class="hljs-regexp">/^[A-Z]{3}$/</span>.test(element);
    <span class="hljs-comment">// otherwise, end function</span>
    <span class="hljs-keyword">if</span> (!isItThreeUpperCaseLetters) {
        <span class="hljs-keyword">return</span>;
    }


    <span class="hljs-comment">// check if all characters are different</span>
    <span class="hljs-keyword">const</span> allDifferentCharacters = element[<span class="hljs-number">0</span>] !== element[<span class="hljs-number">1</span>] &amp;&amp; element[<span class="hljs-number">0</span>] !== element[<span class="hljs-number">2</span>] &amp;&amp; element[<span class="hljs-number">1</span>] !== element[<span class="hljs-number">2</span>];
    <span class="hljs-comment">// if not, return to stop the function</span>
    <span class="hljs-keyword">if</span> (!allDifferentCharacters) {
        <span class="hljs-keyword">return</span>;
    }


    <span class="hljs-comment">// check if it's the first appearence of element inside the array</span>
    <span class="hljs-keyword">const</span> isItFirstAppearence = array.indexOf(element) === index;
    <span class="hljs-comment">// if not, return to stop the function</span>
    <span class="hljs-keyword">if</span> (!isItFirstAppearence) {
        <span class="hljs-keyword">return</span>;
    }


    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}
</code></pre>
<h4 id="heading-and-if-we-didnt-use-a-regular-expression">And if we didn't use a regular expression?</h4>
<p>In the code above, to check three different things, we used a regular expression: <code>/^[A-Z]{3}$/</code>.</p>
<p>But if you don't want to work with regex, you can use the <code>length</code> property to check if a string is of exactly a certain length. In this case <code>element.length === 3</code> to check that the string is exactly three characters long.</p>
<p>Next, the string must be all uppercase and contain only letters.</p>
<p>You can use <code>charCodeAt</code> for this. This method returns the ASCII code of a character, and knowing that uppercase letters have ASCII codes from 65 to 90, you can check that there are only uppercase letters.</p>
<p>There are three numbers to check: <code>element.charCodeAt(0)</code>, <code>element.charCodeAt(1)</code>, and <code>element.charCodeAt(2)</code>. They all need to be between 65 and 90. It's only three characters, but we can still use a loop.</p>
<p>So, that would be as below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i++; i &lt; element.length) {
    <span class="hljs-comment">// find the ASCII code of the character</span>
    <span class="hljs-keyword">const</span> code = element.charCodeAt(i);
    <span class="hljs-comment">// check if it's outside of the range</span>
    <span class="hljs-keyword">if</span> (code &lt; <span class="hljs-number">65</span> || code &gt; <span class="hljs-number">90</span>) {
        <span class="hljs-comment">// if it is, return to stop the function</span>
        <span class="hljs-keyword">return</span>;
    }
}
</code></pre>
<p>Let's add this to the function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params">element, index, array</span>) </span>{

    <span class="hljs-comment">// check that element is a string</span>
    <span class="hljs-keyword">const</span> isNotString = <span class="hljs-keyword">typeof</span> element !== <span class="hljs-string">"string"</span>;
    <span class="hljs-comment">// if it's not, end function</span>
    <span class="hljs-keyword">if</span> (isNotString) {<span class="hljs-keyword">return</span>;}

    <span class="hljs-comment">// check that element has length string</span>
    <span class="hljs-keyword">const</span> hasLengthThree = element.length === <span class="hljs-number">3</span>;
    <span class="hljs-comment">// if it has a different length, end function</span>
    <span class="hljs-keyword">if</span> (!hasLengthThree) {<span class="hljs-keyword">return</span>;}

    <span class="hljs-comment">// loop over the characters</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i++; i &lt; element.length) {
        <span class="hljs-comment">// find the ASCII code of the character</span>
        <span class="hljs-keyword">const</span> code = element.charCodeAt(i);
        <span class="hljs-comment">// check if it's outside of the range</span>
        <span class="hljs-keyword">if</span> (code &lt; <span class="hljs-number">65</span> || code &gt; <span class="hljs-number">90</span>) {
            <span class="hljs-comment">// if it's outside the range, return and stop the function</span>
            <span class="hljs-keyword">return</span>;
        }
    } 
}
</code></pre>
<p>If you have come here from the link above, you can return there to continue reading how to finish the function, otherwise, please continue to the end.</p>
<h3 id="heading-how-to-use-the-example-callback-function">How to use the example callback function</h3>
<p>We have written the callback function. So how do you use it?</p>
<pre><code class="lang-javascript">anArray.every(callbackFunction);
</code></pre>
<p>You can also use the <code>every</code> method inside a callback – maybe the callback to a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter"><code>filter</code> method</a>.</p>
<p>As a program becomes more complex, it's probably going to use proportionally more callback functions.</p>
<h2 id="heading-why-do-we-use-callback-functions-in-javascript">Why do we use callback functions in JavaScript?</h2>
<p>Callback functions are a neat feature of JavaScript. It means we can have a general function that does something (like <code>every</code> that checks if every element in an array match a certain condition, <code>filter</code>, that removes the elements that don't match a certain condition, <code>replace</code>, a string method that accepts a callback to describe how to replace parts of a string, and so on) and a callback function to add specifics of that behaviour for the specific situation.</p>
<ul>
<li><code>filter</code> in that situation will remove the elements specified by the callback.</li>
<li><code>every</code> will check that all the elements in that situation are as specified by the callback function. </li>
<li><code>replace</code> will replace parts of the string in the situation in which it is used as specified by the callback.</li>
</ul>
<p>Higher order functions add a level of abstraction to the code. We don't know (and don't need to know), how <code>every</code> checks every element of the array and verifies that they all pass the tests specified by the callback. We only need to know that the method accepts a callback function for that.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Callbacks are functions that are passed as arguments of other functions. You have seen an example of how to create one, and some considerations on why they are useful.</p>
<p>Thank you for reading!</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[ JavaScript Callback Function –Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ Every JavaScript beginner will face this question at least once: "What is a callback function?"  Well, we can find the answer in the word callback itself. It's all about notifying the caller after the successful completion or failure of a task.  In t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-callback-function-plain-english/</link>
                <guid isPermaLink="false">66bdfff0b51b2616d39af869</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tapas Adhikary ]]>
                </dc:creator>
                <pubDate>Tue, 05 Oct 2021 17:17:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/freeCodeCamp-Cover-4.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Every JavaScript beginner will face this question at least once: "What is a callback function?" </p>
<p>Well, we can find the answer in the word <strong>callback</strong> itself. It's all about notifying the caller after the successful completion or failure of a task. </p>
<p>In this article, I'll focus less on the technical aspects of callbacks and will try to explain how they work in natural language. This should help you understand what a <code>callback function</code> is and why it exists. </p>
<p>If you are a JavaScript beginner, then this article is definitely for you.</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/AUCavCH7FTw" 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-first-what-is-a-function">First, what is a function?</h1>
<p>A function in JavaScript is a set of statements that performs a task. This set of statements can exist without a function, but having them in a function helps us reuse the task in multiple places.</p>
<p>Here is an example of a function that doubles a value if the value is an even number. We pass a number as an argument to the function. The statements inside the function check if the argument is an even number. If so, it doubles it and returns the result. Otherwise, it returns the original number.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doubleEven</span>(<span class="hljs-params">n</span>) </span>{
    <span class="hljs-keyword">if</span> (n % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">return</span> n * <span class="hljs-number">2</span>;
    }
    <span class="hljs-keyword">return</span> n;
}
</code></pre>
<p>Now you can use this function in as many places as you need to:</p>
<pre><code class="lang-js">doubleEven(<span class="hljs-number">10</span>); <span class="hljs-comment">// Output, 20</span>
doubleEven(<span class="hljs-number">5</span>); <span class="hljs-comment">// Output, 5</span>
</code></pre>
<h2 id="heading-you-can-pass-a-function-as-an-argument-to-another-function">You can pass a function as an argument to another function</h2>
<p>In the above example, we saw that you can pass a number as an argument to one function. Likewise, you can pass a function as an argument too. Check this out:</p>
<pre><code class="lang-js"><span class="hljs-comment">/** 
Let's create a foo function that takes a
function as an argument. Here we invoke 
the passed function bar inside foo's body.
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params">bar</span>) </span>{
    bar();
}
</code></pre>
<p>Alright, so how do we now invoke foo?</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
Invoke foo by passing a function as an argument.
*/</span>
foo(<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">'bar'</span>);
}); <span class="hljs-comment">// Output, bar</span>
</code></pre>
<p>Notice that we have passed the entire function definition as an argument to <code>foo</code>. The passed function doesn't have a name. It is called an <code>anonymous function</code>.</p>
<h1 id="heading-what-is-a-callback-function">What is a Callback Function?</h1>
<p>The ability of a JavaScript function to accept another function as an argument is a powerful aspect of the language. </p>
<p>A caller of the function can pass another function as an argument to execute based on any trigger. Let's understand it with the <code>Robin and PizzaHub</code> story.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/pizza.png" alt="Image" width="600" height="400" loading="lazy">
<em>Robin and the PizzaHub Story</em></p>
<p>Robin, a  small boy from Wonderland, loves to eat pizza. One morning he picks up his mother's phone and orders pizza using the PizzaHub app. Robin selects his favorite cheese barbeque pizza and press the order button.</p>
<p>The PizzaHub app registers the order and informs Robin that it will <code>notify</code> him when the pizza is ready and on the way. Robin, the happy boy, waits for a while and finally gets a <code>notification</code> confirming that the pizza is on its way!</p>
<p>So, if we break down the story, the sequence of events goes like this:</p>
<ul>
<li>Robin <code>orders</code> the pizza</li>
<li>The app <code>notes down</code> the order</li>
<li>PizzaHub <code>prepares</code> the pizza, and it is ready after a while.</li>
<li>The app <code>notifies</code> Robin, confirming the pizza is on the way.</li>
</ul>
<p>The mechanism of notifying Robin about the pizza works by using the <code>callback</code> function.</p>
<h2 id="heading-lets-write-the-story-with-programming-language">Let's write the story with programming language</h2>
<p>Yeah, let's do it. The above sequence of events is a set of statements we can put logically in functions.</p>
<p>First Robin orders the pizza. The app registers the order by invoking a function, like this:</p>
<pre><code class="lang-js">orderPizza(<span class="hljs-string">'Veg'</span>, <span class="hljs-string">'Cheese Barbeque'</span>);
</code></pre>
<p>Now the <code>orderPizza()</code> function living somewhere on the PizzaHub server may do some of these actions (it may actually do a lot more than this but let's keep it simple):</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">orderPizza</span>(<span class="hljs-params">type, name</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Pizza ordered...'</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Pizza is for preparation'</span>);
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">let</span> msg = <span class="hljs-string">`Your <span class="hljs-subst">${type}</span> <span class="hljs-subst">${name}</span> Pizza is ready! The total bill is $13`</span>;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`On the Pizzahub server <span class="hljs-subst">${msg}</span>`</span>);
    }, <span class="hljs-number">3000</span>);
}
</code></pre>
<p>The <code>setTimeout</code> function demonstrates that the pizza preparation takes some time. We log a message in the console after the pizza is ready. However, there is a problem!</p>
<p>The message gets logged at the <code>PizzaHub</code> side and poor Robin doesn't have any clue about it. We need to <code>notify</code> him saying the pizza is ready.</p>
<h2 id="heading-introducing-a-callback-function">Introducing a callback function</h2>
<p>We need to introduce a callback function now to let Robin know about the status of the pizza. Let's change the <code>orderPizza</code> function to pass a callback function as an argument. Also notice that we are calling the <code>callback</code> function with the message when the pizza is ready:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">orderPizza</span>(<span class="hljs-params">type, name, callback</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Pizza ordered...'</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Pizza is for preparation'</span>);
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">let</span> msg = <span class="hljs-string">`Your <span class="hljs-subst">${type}</span> <span class="hljs-subst">${name}</span> Pizza is ready! The total bill is $13`</span>;
        callback(msg);
    }, <span class="hljs-number">3000</span>);
}
</code></pre>
<p>Now, let's make changes to the invocation of the <code>orderPizza</code> function:</p>
<pre><code class="lang-js">orderPizza(<span class="hljs-string">'Veg'</span>, <span class="hljs-string">'Cheese Barbeque'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">message</span>)</span>{
    <span class="hljs-built_in">console</span>.log(message);
});
</code></pre>
<p>So now the caller will be notified using the callback function once the pizza is ready. Isn't that so useful?</p>
<h1 id="heading-in-summary">In Summary</h1>
<p>To Summarize:</p>
<ul>
<li>A JavaScript function can accept another function as an argument.</li>
<li>Passing the function as an argument is a powerful programming concept that can be used to notify a caller that something happened. It is also known as the callback function.</li>
<li>You can use callback functions to notify the caller depending on a use case. Callbacks are also used to carry out certain tasks depending on the state (pass, fail) of other tasks.</li>
<li>But be careful – nesting too many callback functions may not be a great idea and may create <code>Callback Hell</code>. We will learn more about this in an upcoming article.</li>
</ul>
<p>Thanks for reading! You can learn more from this open source repository about asynchronous programming. Don't forget to try the quizzes.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/atapas/promise-interview-ready">https://github.com/atapas/promise-interview-ready</a></div>
<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 informative.</p>
<p>Let's connect. You can follow me on <a target="_blank" href="https://twitter.com/tapasadhikary">Twitter (@tapasadhikary)</a>, on 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>Are you interested to lean more about JavaScript asynchronous concepts? Here are a few links to help you out:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript/">Synchronous vs Asynchronous JavaScript – Call Stack, Promises, and More</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/series/javascript-promises">An article series on JavaScript Promises &amp; Async/Await</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=pIjfzjsoVw4&amp;list=PLIJrr73KDmRyCanrlIS8PEOF0kPKgI8jN">A video series on JavaScript Asynchronous programming</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Synchronous vs Asynchronous JavaScript – Call Stack, Promises, and More ]]>
                </title>
                <description>
                    <![CDATA[ Let me start this article by asking, "What is JavaScript"? Well, here's the most confusing yet to-the-point answer I have found so far: JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript/</link>
                <guid isPermaLink="false">66be001e422f318982ba47cd</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tapas Adhikary ]]>
                </dc:creator>
                <pubDate>Mon, 13 Sep 2021 21:00:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/freeCodeCamp-Cover-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Let me start this article by asking, "What is JavaScript"? Well, here's the most confusing yet to-the-point answer I have found so far:</p>
<blockquote>
<p>JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibility.</p>
</blockquote>
<p>Hold on a second – did it say single-threaded and asynchronous at the same time? If you understand what single-threaded means, you'll likely mostly associate it with synchronous operations. How can JavaScript be asynchronous, then?</p>
<p>In this article, we will learn all about the synchronous and asynchronous parts of JavaScript. You use both in web programming almost daily. </p>
<p>If you like to learn from video content as well, this article is also available as a video tutorial here: 🙂</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/pIjfzjsoVw4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h1 id="heading-in-this-article-youll-learn">In this article, You'll Learn:</h1>
<ul>
<li>How JavaScript is synchronous.</li>
<li>How asynchronous operations occur when JavaScript is single-threaded.</li>
<li>How understanding synchronous vs. asynchronous helps you better understand JavaScript promises.</li>
<li>Lots of simple but powerful examples to cover these concepts in detail.</li>
</ul>
<h1 id="heading-javascript-functions-are-first-class-citizens">JavaScript Functions are First-Class Citizens</h1>
<p>In JavaScript, you can create and modify a function, use it as an argument, return it from another function, and assign it to a variable. All these abilities allow us to use functions everywhere to place a bunch of code logically.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/block-function.png" alt="Image" width="600" height="400" loading="lazy">
<em>Lines of code organized into functions logically</em></p>
<p>We need to tell the JavaScript engine to execute functions by invoking them. It'll look like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Do something</span>
    <span class="hljs-comment">// Do something again</span>
    <span class="hljs-comment">// Again</span>
    <span class="hljs-comment">// So on...</span>
}

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

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

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

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

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

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

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

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

    f2();
}

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

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

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

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

    <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span>
        resolve(<span class="hljs-string">'I am a promise'</span>)
    ).then(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(resolve))

    f2();
}

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

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

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

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

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

  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span>
    resolve(<span class="hljs-string">'I am a Promise, right after f1 and f3! Really?'</span>)
  ).then(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(resolve));

  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span>
    resolve(<span class="hljs-string">'I am a Promise after Promise!'</span>)
  ).then(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(resolve));

  f2();
}

main();
</code></pre>
<p>Here is the expected output:</p>
<pre><code class="lang-shell">main
f2
I am a Promise, right after f1 and f3! Really?
I am a Promise after Promise!
f3
f1
</code></pre>
<p>Do you want more such quizzes? <a target="_blank" href="https://github.com/atapas/promise-interview-ready">Head over to this repository</a> to practice more exercises.</p>
<p>In case you are stuck or need any clarifications, my DM is always <a target="_blank" href="https://twitter.com/tapasadhikary">open on Twitter</a>.</p>
<h1 id="heading-in-summary">In Summary</h1>
<p>To summarize:</p>
<ul>
<li>The JavaScript engine uses the stack data structure to keep track of currently executed functions. The stack is called the function execution stack.</li>
<li>The function execution stack (aka call stack) executes the functions sequentially, line-by-line, one-by-one.</li>
<li>The browser/web APIs use callback functions to complete the tasks when an asynchronous operation/delay is done. The callback function is placed in the callback queue.</li>
<li>The promise executor functions are placed in the job queue.</li>
<li>For each loop of the event loop, one macro task is completed out of the callback queue.</li>
<li>Once that task is complete, the event loop visits the job queue. It completes all the micro-tasks in the job queue before it looks for the next thing.</li>
<li>If both the queues get entries at the same point in time, the job queue gets preference over the callback queue.</li>
</ul>
<h1 id="heading-before-we-end">Before We End...</h1>
<p>That's all for now. I hope you've found this article insightful, and that it helps you understand JavaScript's synchronous vs asynchronous concepts better.</p>
<p>Let's connect. You can follow me on <a target="_blank" href="https://twitter.com/tapasadhikary">Twitter(@tapasadhikary)</a>, My <a target="_blank" href="https://youtube.com/c/TapasAdhikary?sub_confirmation=1">Youtube channel</a>, and <a target="_blank" href="https://github.com/atapas">GitHub(atapas)</a>.</p>
<p>As promised before, here are a few articles you may find useful,</p>
<ul>
<li><a target="_blank" href="https://blog.greenroots.info/javascript-promises-explain-like-i-am-five">JavaScript Promises - Explain Like I'm Five</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/javascript-promise-chain-the-art-of-handling-promises">JavaScript Promise Chain - The art of handling promises</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/javascript-async-and-await-in-plain-english-please">JavaScript async and await - in plain English, please</a></li>
<li><a target="_blank" href="https://blog.greenroots.info/introducing-promiviz-visualize-and-learn-javascript-promise-apis">Introducing PromiViz - visualize and learn JavaScript promise APIs</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Async/Await Tutorial – Learn Callbacks, Promises, and Async/Await in JS by Making Ice Cream 🍧🍨🍦 ]]>
                </title>
                <description>
                    <![CDATA[ Today we're going to build and run an ice cream shop and learn asynchronous JavaScript at the same time. Along the way, you'll learn how to use: Callbacks Promises Async / Await Here's what we'll cover in this article: What is Asynchronous JavaSc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-async-await-tutorial-learn-callbacks-promises-async-await-by-making-icecream/</link>
                <guid isPermaLink="false">66b2095aa5be9a107f4341cd</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joy Shaheb ]]>
                </dc:creator>
                <pubDate>Wed, 02 Jun 2021 14:45:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/FCC-Thumbnail--3-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Today we're going to build and run an <strong>ice cream shop</strong> and learn <strong>asynchronous JavaScript</strong> at the same time. Along the way, you'll learn how to use:</p>
<ul>
<li>Callbacks</li>
<li>Promises</li>
<li>Async / Await</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1j935dg72g9u8zvh2oi.png" alt="Alt Text" width="1107" height="576" loading="lazy"></p>
<h1 id="heading-heres-what-well-cover-in-this-article">Here's what we'll cover in this article:</h1>
<ul>
<li>What is Asynchronous JavaScript?</li>
<li>Synchronous vs Asynchronous JavaScript</li>
<li>How Callbacks Work in JavaScript</li>
<li>How Promises Work in JavaScript</li>
<li>How Async / Await Works in JavaScript</li>
</ul>
<p>So let's dive in!</p>
<h2 id="heading-you-can-watch-this-tutorial-on-youtube-as-well-if-you-like">You can watch this tutorial on YouTube as well if you like:</h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/n5ZtTO1ArWg" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h1 id="heading-what-is-asynchronous-javascript">What is Asynchronous JavaScript?</h1>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7yd96tgxvuowqmfgcx6b.png" alt="Alt Text" width="1498" height="703" loading="lazy"></p>
<p>If you want to build projects efficiently, then this concept is for you.</p>
<p>The theory of async JavaScript helps you break down big complex projects into smaller tasks.</p>
<p>Then you can use any of these three techniques – <strong>callbacks, promises or Async/await</strong> – to run those small tasks in a way that you get the best results.</p>
<p>Let's dive in!🎖️</p>
<h1 id="heading-synchronous-vs-asynchronous-javascript">Synchronous vs Asynchronous JavaScript</h1>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/arzbf1rc3pi4yi6u8wup.png" alt="Alt Text" width="1253" height="642" loading="lazy"></p>
<h2 id="heading-what-is-a-synchronous-system">What is a Synchronous System?</h2>
<p>In a synchronous system, tasks are completed one after another.</p>
<p>Think of this as if you have just one hand to accomplish 10 tasks. So, you have to complete one task at a time.</p>
<p>Take a look at the GIF 👇 – one thing is happening at a time here:</p>
<p><img src="https://media.giphy.com/media/ICIS16DkE9qB9HVxtq/giphy.gif" alt="Synchronous System" width="480" height="258" loading="lazy"></p>
<p>You'll see that until the first image is loaded completely, the second image doesn't start loading.</p>
<p>Well, JavaScript is by default Synchronous <strong>[single threaded]</strong>. Think about it like this – one thread means one hand with which to do stuff.</p>
<h2 id="heading-what-is-an-asynchronous-system">What is an Asynchronous System?</h2>
<p>In this system, tasks are completed independently.</p>
<p>Here, imagine that for 10 tasks, you have 10 hands. So, each hand can do each task independently and at the same time.</p>
<p>Take a look at the GIF 👇 – you can see that each image loads at the same time.</p>
<p><img src="https://media.giphy.com/media/MMDnmJnE7uhX6KtcKc/giphy.gif" alt="Asynchronous System" width="480" height="258" loading="lazy"></p>
<p>Again, all the images are loading at their own pace. None of them is waiting for any of the others.</p>
<h2 id="heading-to-summarize-synchronous-vs-asynchronous-js">To Summarize Synchronous vs Asynchronous JS:</h2>
<p>When three images are on a marathon, in a:</p>
<ul>
<li><strong>Synchronous</strong> system, three images are in the same lane. One can't overtake the other. The race is finished one by one. If image number 2 stops, the following image stops.</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w1r9y4ghhq0t8wjb1u9h.png" alt="Alt Text" width="1544" height="748" loading="lazy"></p>
<ul>
<li><strong>Asynchronous system,</strong> the three images are in different lanes. They'll finish the race on their own pace. Nobody stops for anybody:</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehknx5shc4orh32s0ktk.png" alt="Alt Text" width="1544" height="748" loading="lazy"></p>
<h2 id="heading-synchronous-and-asynchronous-code-examples">Synchronous and Asynchronous Code Examples</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pzbnpcza9rbj8xgiby95.png" alt="Alt Text" width="1156" height="511" loading="lazy"></p>
<p>Before starting our project, let's look at some examples and clear up any doubts.</p>
<h3 id="heading-synchronous-code-example">Synchronous Code Example</h3>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5m6p1qy522lj3auvl5ty.png" alt="Alt Text" width="1054" height="421" loading="lazy"></p>
<p>To test a synchronous system, write this code in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">" I "</span>);

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

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

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

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

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

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

  call_production();
};

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

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

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

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

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

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

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

  call_production();
};

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

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


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

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

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

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

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

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

      resolve( )

    }

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

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

    }

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

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

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

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

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

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

    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    <span class="hljs-keyword">catch</span>(error){
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"customer left"</span>)
    }
}
</code></pre>
<p>And here's the result: 👇</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qs9yccq9209u7m9lquju.png" alt="Alt Text" width="1221" height="607" loading="lazy"></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Congratulations for reading until the end! In this article you've learned: </p>
<ul>
<li>The difference between synchronous and asynchronous systems</li>
<li>Mechanisms of asynchronous JavaScript using 3 techniques (callbacks, promises, and Async/ Await)</li>
</ul>
<p>Here's your medal for reading until the end. ❤️</p>
<h3 id="heading-suggestions-and-criticisms-are-highly-appreciated">Suggestions and criticisms are highly appreciated ❤️</h3>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/usxsz1lstuwry3jlly4d.png" alt="Alt Text" width="1000" height="245" loading="lazy"></p>
<p><strong>YouTube <a target="_blank" href="https://youtube.com/c/joyshaheb">/ Joy Shaheb</a></strong></p>
<p><strong>LinkedIn <a target="_blank" href="https://www.linkedin.com/in/joyshaheb/">/ JoyShaheb</a></strong></p>
<p><strong>Twitter <a target="_blank" href="https://twitter.com/JoyShaheb">/ JoyShaheb</a></strong></p>
<p><strong>Instagram <a target="_blank" href="https://www.instagram.com/joyshaheb/">/ JoyShaheb</a></strong></p>
<h1 id="heading-credits">Credits</h1>
<ul>
<li><a target="_blank" href="https://www.freepik.com/user/collections/promises-article/2046500">Collection of all the images used</a></li>
<li><a target="_blank" href="https://www.flaticon.com/packs/unicorn-4">Unicorns</a>, <a target="_blank" href="https://www.flaticon.com/packs/kitty-avatars-3">kitty avatar</a></li>
<li><a target="_blank" href="https://www.pexels.com/photo/brown-tabby-cat-with-slice-of-loaf-bread-on-head-4587955/">tabby cat</a>, <a target="_blank" href="https://www.pexels.com/photo/young-female-astrologist-predicting-future-with-shining-ball-6658693/">Astrologist Woman</a>, <a target="_blank" href="https://www.pexels.com/photo/woman-in-white-dress-holding-white-flower-bouquet-3981511/">girl-holding-flower</a></li>
<li><a target="_blank" href="https://www.vecteezy.com/vector-art/180695-people-mind-emotion-character-cartoon-vector-illustration">Character emotions</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Callback Functions – What are Callbacks in JS and How to Use Them ]]>
                </title>
                <description>
                    <![CDATA[ By Cem Eygi If you’re familiar with programming, you already know what functions do and how to use them. But what is a callback function? Callback functions are an important part of JavaScript and once you understand how callbacks work, you’ll become... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-callback-functions-what-are-callbacks-in-js-and-how-to-use-them/</link>
                <guid isPermaLink="false">66d45def182810487e0ce11b</guid>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 17 Mar 2020 16:18:05 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/03/caspar-camille-rubin-7SDoly3FV_0-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Cem Eygi</p>
<p>If you’re familiar with programming, you already know what functions do and how to use them. But what is a callback function? Callback functions are an important part of JavaScript and once you understand how callbacks work, you’ll become much better in JavaScript.</p>
<p>So in this post, I would like to help you to understand what callback functions are and how to use them in JavaScript by going through some examples.</p>
<h2 id="heading-what-is-a-callback-function">What is a Callback Function?</h2>
<p>In JavaScript, functions are objects. Can we pass objects to functions as parameters? Yes.</p>
<p>So, we can also pass functions as parameters to other functions and call them inside the outer functions. Sounds complicated? Let me show that in an example below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params">callback</span>) </span>{  
    callback();
}
</code></pre>
<p>The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function. But that’s not all.</p>
<p><strong>You can also watch the video version of callback functions below:</strong></p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/qtfi4-8dj9c" 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>
<h3 id="heading-why-do-we-need-callback-functions">Why do we need Callback Functions?</h3>
<p>JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.</p>
<p>Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.</p>
<p>In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened or some task is completed. Let’s see how…</p>
<h2 id="heading-how-to-create-a-callback">How to create a Callback</h2>
<p>To understand what I’ve explained above, let me start with a simple example. We want to log a message to the console but it should be there after 3 seconds.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> message = <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">"This message is shown after 3 seconds"</span>);
}

<span class="hljs-built_in">setTimeout</span>(message, <span class="hljs-number">3000</span>);
</code></pre>
<p>There is a built-in method in JavaScript called “setTimeout”, which calls a function or evaluates an expression after a given period of time (in milliseconds). So here, the “message” function is being called after 3 seconds have passed. (1 second = 1000 milliseconds)</p>
<p>In other words, the message function is being called after something happened (after 3 seconds passed for this example), but not before. So the message function is an example of a callback function.</p>
<h3 id="heading-what-is-an-anonymous-function">What is an Anonymous Function?</h3>
<p>Alternatively, we can define a function directly inside another function, instead of calling it. It will look like this:</p>
<pre><code class="lang-javascript"><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">"This message is shown after 3 seconds"</span>);
}, <span class="hljs-number">3000</span>);
</code></pre>
<p>As we can see, the callback function here has no name and a function definition without a name in JavaScript is called as an “anonymous function”. This does exactly the same task as the example above.</p>
<h3 id="heading-callback-as-an-arrow-function">Callback as an Arrow Function</h3>
<p>If you prefer, you can also write the same callback function as an ES6 arrow function, which is a newer type of function in JavaScript:</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">"This message is shown after 3 seconds"</span>);
}, <span class="hljs-number">3000</span>);
</code></pre>
<h2 id="heading-what-about-events">What about Events?</h2>
<p>JavaScript is an event-driven programming language. We also use callback functions for event declarations. For example, let’s say we want users to click on a button:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"callback-btn"</span>&gt;</span>Click here<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>This time we will see a message on the console only when the user clicks on the button:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.queryselector(<span class="hljs-string">"#callback-btn"</span>)
    .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">"User has clicked on the button!"</span>);
});
</code></pre>
<p>So here we select the button first with its id, and then we add an event listener with the addEventListener method. It takes 2 parameters. The first one is its type, “click”, and the second parameter is a callback function, which logs the message when the button is clicked.</p>
<p>As you can see, callback functions are also used for event declarations in JavaScript.</p>
<h2 id="heading-wrap-up">Wrap up</h2>
<p>Callbacks are used often in JavaScript, and I hope this post helps you understand what they actually do and how to work with them easier. Next, you can learn about <a target="_blank" href="https://www.freecodecamp.org/news/javascript-es6-promises-for-beginners-resolve-reject-and-chaining-explained/">JavaScript Promises</a> which is a similar topic that I've explained in my new post.</p>
<p><strong>If you want to learn more about web development, feel free to</strong> <a target="_blank" href="https://www.youtube.com/channel/UC1EgYPCvKCXFn8HlpoJwY3Q"><strong>follow me on Youtube</strong></a><strong>!</strong></p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Your Own Promisify Function from Scratch ]]>
                </title>
                <description>
                    <![CDATA[ By Shailesh Shekhawat Introduction In this article, you will learn how to write your own promisify function from scratch. Promisification helps in dealing with callback-based APIs while keeping code consistent with promises. We could just wrap any fu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/write-your-own-promisify-function-from-scratch/</link>
                <guid isPermaLink="false">66d4615a7df3a1f32ee7f8b2</guid>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 22 Dec 2019 06:39:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/12/write.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shailesh Shekhawat</p>
<h3 id="heading-introduction">Introduction</h3>
<p>In this article, you will learn how to write your own promisify function from scratch.</p>
<p>Promisification helps in dealing with callback-based APIs while keeping code consistent with promises.</p>
<p>We could just wrap any function with <code>new Promise()</code> and not worry about it at all. But doing that when we have many functions would be redundant.</p>
<p>If you understand promises and callbacks, then learning how to write promisify functions should be easy. So let's get started.</p>
<h3 id="heading-but-have-you-ever-wondered-how-promisify-works">But have you ever wondered how promisify works?</h3>
<blockquote>
<p>The important thing is not to stop questioning. Curiosity has its own reason for existence.  </p>
<p>— Albert Einstein</p>
</blockquote>
<p>Promises were introduced in the <a target="_blank" href="http://www.ecma-international.org/ecma-262/6.0/">ECMA-262 Standard, 6th Edition</a> (ES6) that was published in June 2015.</p>
<p>It was quite an improvement over callbacks, as we all know how unreadable "callback hell" can be :)</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/callback-1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As a Node.js developer, you should know <a target="_blank" href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261">what a promise is</a> and <a target="_blank" href="https://101node.io/blog/how-promises-actually-work-inside-out/">how it works internally</a>, which will also help you in JS interviews. Feel free to review them quickly before reading on.</p>
<h3 id="heading-why-do-we-need-to-convert-callbacks-to-promises">Why do we need to convert callbacks to promises?</h3>
<ol>
<li>With callbacks, if you want to do something sequentially you will have to specify an <code>err</code> argument in each callback, which is redundant. In promises or async-await, you can just add a <code>.catch</code> method or block which will catch any errors that occurred in the promise chain</li>
<li>With callbacks, you have no control over when it's called, under what context, or how many times it's being called, which can lead to memory leaks.</li>
<li>Using promises, we control these factors (especially error handling) so the code is more readable and maintainable.</li>
</ol>
<h2 id="heading-how-to-make-callback-based-functions-return-a-promise">How to make callback-based functions return a promise</h2>
<p>There are two ways to do it:</p>
<ol>
<li>Wrap the function in another function which returns a promise. It then resolves or rejects based on callback arguments.</li>
<li>Promisification — We create a util/helper function <code>promisify</code> which will transform all error first callback-based APIs.</li>
</ol>
<p>Example: there’s a callback-based API which provides the sum of two numbers. We want to promisify it so it returns a <code>thenable</code> promise.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getSumAsync = <span class="hljs-function">(<span class="hljs-params">num1, num2, callback</span>) =&gt;</span> {

  <span class="hljs-keyword">if</span> (!num1 || !num2) {
    <span class="hljs-keyword">return</span> callback(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Missing arguments"</span>), <span class="hljs-literal">null</span>);
  }
  <span class="hljs-keyword">return</span> callback(<span class="hljs-literal">null</span>, num1 + num2);
}
getSumAsync(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err){
    doSomethingWithError(err)
  }<span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// 2</span>
  }
})
</code></pre>
<h3 id="heading-wrap-into-a-promise">Wrap into a promise</h3>
<p>As you can see, <code>getSumPromise</code> delegates all the work to the original function <code>getSumAsync</code>, providing its own callback that translates to promise <code>resolve/reject</code>.</p>
<h3 id="heading-promisify">Promisify</h3>
<p>When we need to promisify many functions we can create a helper function <code>promisify</code>.</p>
<h3 id="heading-what-is-promisification">What is Promisification?</h3>
<p>Promisification means transformation. It’s a conversion of a function that accepts a callback into a function returning a promise.</p>
<p>Using Node.js's <code>util.promisify()</code>:</p>
<pre><code><span class="hljs-keyword">const</span> { promisify } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'util'</span>)
<span class="hljs-keyword">const</span> getSumPromise = promisify(getSumAsync) <span class="hljs-comment">// step 1</span>
getSumPromise(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>) <span class="hljs-comment">// step 2</span>
.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(result)
})
.catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span>{
  doSomethingWithError(err);
})
</code></pre><p>So it looks like a magic function which is transforming <code>getSumAsync</code> into <code>getSumPromise</code> which has <code>.then</code> and <code>.catch</code> methods</p>
<h3 id="heading-lets-write-our-own-promisify-function">Let’s write our own promisify function:</h3>
<p>If you look at <strong>step 1</strong> in the above code, the <code>promisify</code> function accepts a function as an argument, so the first thing we have to do write a function that can do the same:</p>
<pre><code><span class="hljs-keyword">const</span> getSumPromise = myPromisify(getSumAsync)
<span class="hljs-keyword">const</span> myPromisify = <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> {}
</code></pre><p>After that, <code>getSumPromise(1, 1)</code> is a function call. This means that our promisify should return another function which can be called with the same arguments of the original function:</p>
<pre><code><span class="hljs-keyword">const</span> myPromisify = <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> {
 <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> {
 }
}
</code></pre><p>In the above code you can see we are <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spreading</a> arguments because we don’t know how many arguments the original function has. <code>args</code> will be an array containing all the arguments.</p>
<p>When you call <code>getSumPromise(1, 1)</code> you’re actually calling <code>(...args)=&gt; {}</code>. In the implementation above it returns a promise. That’s why you’re able to use <code>getSumPromise(1, 1).then(..).catch(..)</code>.</p>
<p>I hope you’ve gotten the hint that the wrapper function <code>(...args) =&gt; {}</code> should return a promise.</p>
<h3 id="heading-return-a-promise">Return a promise</h3>
<pre><code><span class="hljs-keyword">const</span> myPromisify = <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {

    })
  }
}
</code></pre><p>Now the tricky part is how to decide when to <code>resolve or reject</code> a promise.<br>Actually, that will be decided by the original <code>getSumAsync</code> function implementation – it will call the original callback function and we just need to define it. Then based on <code>err</code> and <code>result</code> we will <code>reject</code> or  <code>resolve</code> the promise.</p>
<pre><code><span class="hljs-keyword">const</span> myPromisify = <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">...args</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-function"><span class="hljs-keyword">function</span> <span class="hljs-title">customCallback</span>(<span class="hljs-params">err, result</span>) </span>{
       <span class="hljs-keyword">if</span> (err) {
         reject(err)
       }<span class="hljs-keyword">else</span> {
         resolve(result);
        }
      }
   })
  }
}
</code></pre><p>Our <code>args[]</code> only consists of arguments passed by <code>getSumPromise(1, 1)</code> except the callback function. So you need to add <code>customCallback(err, result)</code> to the <code>args[]</code>which the original function <code>getSumAsync</code> will call accordingly as we are tracking the result in <code>customCallback</code>.</p>
<h3 id="heading-push-customcallback-to-args">Push customCallback to args[]</h3>
<pre><code><span class="hljs-keyword">const</span> myPromisify = <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> {
   <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">...args</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-function"><span class="hljs-keyword">function</span> <span class="hljs-title">customCallback</span>(<span class="hljs-params">err, result</span>) </span>{
         <span class="hljs-keyword">if</span> (err) {
           reject(err)
         }<span class="hljs-keyword">else</span> {
          resolve(result);
         }
        }
        args.push(customCallback)
        fn.call(<span class="hljs-built_in">this</span>, ...args)
      })
  }
}
</code></pre><p>As you can see, we have added <code>fn.call(this, args)</code>, which will call the original function under the same context with the arguments <code>getSumAsync(1, 1, customCallback)</code>. Then our promisify function should be able to <code>resolve/reject</code> accordingly.</p>
<p>The above implementation will work when the original function expects a callback with two arguments, <code>(err, result)</code>. That’s what we encounter most often. Then our custom callback is in exactly the right format and <code>promisify</code> works great for such a case.</p>
<p><strong>But what if the original</strong> <code>**fn**</code> <strong>expects a callback with more arguments</strong> like <code>**callback(err, result1, result2, ...)**</code><strong>?</strong></p>
<p>In order to make it compatible with that, we need to modify our <code>myPromisify</code> function which will be an advanced version.</p>
<pre><code><span class="hljs-keyword">const</span> myPromisify = <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> {
   <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">...args</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-function"><span class="hljs-keyword">function</span> <span class="hljs-title">customCallback</span>(<span class="hljs-params">err, ...results</span>) </span>{
         <span class="hljs-keyword">if</span> (err) {
           <span class="hljs-keyword">return</span> reject(err)
         }
         <span class="hljs-keyword">return</span> resolve(results.length === <span class="hljs-number">1</span> ? results[<span class="hljs-number">0</span>] : results) 
        }
        args.push(customCallback)
        fn.call(<span class="hljs-built_in">this</span>, ...args)
      })
   }
}
</code></pre><p>Example:</p>
<pre><code><span class="hljs-keyword">const</span> getSumAsync = <span class="hljs-function">(<span class="hljs-params">num1, num2, callback</span>) =&gt;</span> {

  <span class="hljs-keyword">if</span> (!num1 || !num2) {
    <span class="hljs-keyword">return</span> callback(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Missing dependencies"</span>), <span class="hljs-literal">null</span>);
  }

  <span class="hljs-keyword">const</span> sum = num1 + num2;
  <span class="hljs-keyword">const</span> message = <span class="hljs-string">`Sum is <span class="hljs-subst">${sum}</span>`</span>
  <span class="hljs-keyword">return</span> callback(<span class="hljs-literal">null</span>, sum, message);
}
<span class="hljs-keyword">const</span> getSumPromise = myPromisify(getSumAsync)
getSumPromise(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>).then(arrayOfResults) <span class="hljs-comment">// [6, 'Sum is 6']</span>
</code></pre><p>That’s all! Thank you for making it this far!</p>
<p>I hope you’re able to grasp the concept. Try to re-read it again. It’s a bit of code to wrap your head around, but not too complex. Let me know if it was helpful ?</p>
<p>Don’t forget to share it with your friends who are starting with Node.js or need to level up their Node.js skills.</p>
<p>References:</p>
<p><a target="_blank" href="https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original">https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original</a></p>
<p><a target="_blank" href="https://github.com/digitaldesignlabs/es6-promisify">https://github.com/digitaldesignlabs/es6-promisify</a></p>
<p><em>You can read other articles like this at <a target="_blank" href="https://101node.io/blog/write-your-own-promisify-function-from-scratch/">101node.io</a>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Callback Function in JavaScript? ]]>
                </title>
                <description>
                    <![CDATA[ This article gives a brief introduction to the concept and usage of callback functions in the JavaScript programming language. Functions are Objects The first thing we need to know is that in Javascript, functions are first-class objects. As such, we... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-callback-function-in-javascript/</link>
                <guid isPermaLink="false">66c36591693ce41cd86e798e</guid>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 14 Dec 2019 23:50:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9eb0740569d1a4ca3e8d.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>This article gives a brief introduction to the concept and usage of callback functions in the JavaScript programming language.</p>
<h2 id="heading-functions-are-objects"><strong>Functions are Objects</strong></h2>
<p>The first thing we need to know is that in Javascript, functions are first-class objects. As such, we can work with them in the same way we work with other objects, like assigning them to variables and passing them as arguments into other functions. This is important, because it’s the latter technique that allows us to extend functionality in our applications.</p>
<h2 id="heading-callback-functions"><strong>Callback Functions</strong></h2>
<p>A <strong>callback function</strong> is a function that is passed <em>as an argument</em> to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a <strong>higher-order function</strong>, which contains the logic for <em>when</em> the callback function gets executed. It’s the combination of these two that allow us to extend our functionality.</p>
<p>To illustrate callbacks, let’s start with a simple example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createQuote</span>(<span class="hljs-params">quote, callback</span>)</span>{ 
  <span class="hljs-keyword">var</span> myQuote = <span class="hljs-string">"Like I always say, "</span> + quote;
  callback(myQuote); <span class="hljs-comment">// 2</span>
}

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

createQuote(<span class="hljs-string">"eat your vegetables!"</span>, logQuote); <span class="hljs-comment">// 1</span>

<span class="hljs-comment">// Result in console: </span>
<span class="hljs-comment">// Like I always say, eat your vegetables!</span>
</code></pre>
<p>In the above example, <code>createQuote</code> is the higher-order function, which accepts two arguments, the second one being the callback. The <code>logQuote</code> function is being used to pass in as our callback function. When we execute the <code>createQuote</code> function <em>(1)</em>, notice that we are <em>not appending</em> parentheses to <code>logQuote</code> when we pass it in as an argument. This is because we do not want to execute our callback function right away, we simply want to pass the function definition along to the higher-order function so that it can be executed later.</p>
<p>Also, we need to ensure that if the callback function we pass in expects arguments, that we supply those arguments when executing the callback <em>(2)</em>. In the above example, that would be the <code>callback(myQuote);</code> statement, since we know that <code>logQuote</code> expects a quote to be passed in.</p>
<p>Additionally, we can pass in anonymous functions as callbacks. The below call to <code>createQuote</code> would have the same result as the above example:</p>
<pre><code class="lang-javascript">createQuote(<span class="hljs-string">"eat your vegetables!"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">quote</span>)</span>{ 
  <span class="hljs-built_in">console</span>.log(quote); 
});
</code></pre>
<p>Incidentally, you don’t <em>have</em> to use the word “callback” as the name of your argument, Javascript just needs to know that it’s the correct argument name. Based on the above example, the below function will behave in exactly the same manner.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createQuote</span>(<span class="hljs-params">quote, functionToCall</span>) </span>{ 
  <span class="hljs-keyword">var</span> myQuote = <span class="hljs-string">"Like I always say, "</span> + quote;
  functionToCall(myQuote);
}
</code></pre>
<h2 id="heading-why-use-callback-functions"><strong>Why use Callback functions?</strong></h2>
<p>Most of the time we are creating programs and applications that operate in a <strong>synchronous</strong> manner. In other words, some of our operations are started only after the preceding ones have completed. Often when we request data from other sources, such as an external API, we don’t always know <em>when</em> our data will be served back. In these instances we want to wait for the response, but we don’t always want our entire application grinding to a halt while our data is being fetched. These situations are where callback functions come in handy.</p>
<p>Let’s take a look at an example that simulates a request to a server:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">serverRequest</span>(<span class="hljs-params">query, callback</span>)</span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">var</span> response = query + <span class="hljs-string">"full!"</span>;
    callback(response);
  },<span class="hljs-number">5000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getResults</span>(<span class="hljs-params">results</span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Response from the server: "</span> + results);
}

serverRequest(<span class="hljs-string">"The glass is half "</span>, getResults);

<span class="hljs-comment">// Result in console after 5 second delay:</span>
<span class="hljs-comment">// Response from the server: The glass is half full!</span>
</code></pre>
<p>In the above example, we make a mock request to a server. After 5 seconds elapse the response is modified and then our callback function <code>getResults</code> gets executed. To see this in action, you can copy/paste the above code into your browser’s developer tool and execute it.</p>
<p>Also, if you are already familiar with <code>setTimeout</code>, then you’ve been using callback functions all along. The anonymous function argument passed into the above example’s <code>setTimeout</code> function call is also a callback! So the example’s original callback is actually executed by another callback. Be careful not to nest too many callbacks if you can help it, as this can lead to something called “callback hell”! As the name implies, it isn’t a joy to deal with.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
