<?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" version="2.0"><channel><title><![CDATA[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://blog.fraddyoliveira.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 16:14:51 GMT</lastBuildDate><atom:link href="https://blog.fraddyoliveira.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Change Callbacks to Promises in JavaScript]]></title><description><![CDATA[Introduction
Handling asynchronous operations with callbacks can be tedious, while handling them with promises is more efficient. However, managing asynchronous operations with async/await is exceptionally effective.
In this article, we will learn ho...]]></description><link>https://blog.fraddyoliveira.com/how-to-convert-callback-to-promise-in-javascript-d809774c7cc4</link><guid isPermaLink="true">https://blog.fraddyoliveira.com/how-to-convert-callback-to-promise-in-javascript-d809774c7cc4</guid><category><![CDATA[callstack]]></category><category><![CDATA[promises]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Fraddy Oliveira]]></dc:creator><pubDate>Fri, 29 Oct 2021 05:41:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717479240590/9baf5230-5de0-4fc5-bf67-2d23b1aded7d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Handling asynchronous operations with <strong>callbacks can be tedious</strong>, while handling them with <strong>promises is more efficient</strong>. However, managing asynchronous operations with <code>async</code><strong>/</strong><code>await</code> <strong>is exceptionally effective.</strong></p>
<p>In this article, <strong>we will learn how to convert traditional callbacks to promises</strong>.</p>
<h3 id="heading-prerequisite">Prerequisite</h3>
<ul>
<li><p>Understanding how to use callback functions.</p>
</li>
<li><p>Understanding how to use promises in JavaScript.</p>
</li>
</ul>
<h2 id="heading-why-use-promises-instead-of-callbacks">Why use promises instead of callbacks?</h2>
<p>The callback has many limitations:</p>
<ul>
<li><p>Managing asynchronous requests</p>
</li>
<li><p>Poor code readability</p>
</li>
<li><p>Difficult error handling</p>
</li>
</ul>
<p>To address these issues, we should use promises. To learn how promises work, check out my article <a target="_blank" href="https://blog.fraddyoliveira.com/promises-in-javascript-c9764cba4a23"><strong>click here</strong></a>.</p>
<h2 id="heading-why-convert-callbacks-to-promises">Why convert callbacks to promises?</h2>
<p>Promises were introduced in Javascript in ES6 (also know as ECMAScript 2015).</p>
<p>Before ES6, only callbacks could handle asynchronous operations. Many libraries or applications written before ES6 use callbacks. These codebases may still use callbacks because they are not actively maintained or upgrading them requires significant effort.</p>
<p>We will learn how to convert callbacks to promises using the <strong>NodeJs module</strong> and also write a <strong>generic function for this purpose</strong>.</p>
<h2 id="heading-methods-to-convert-callbacks-to-promises">Methods to convert callbacks to promises:</h2>
<h3 id="heading-1-basic-approach"><strong>1) Basic approach</strong></h3>
<p>With this approach, we will get a <strong>basic understanding of how to convert a callback to a promise</strong>. Let’s learn through an example.</p>
<p>Consider an example based on the <strong>browser</strong> <code>onload</code> <strong>event</strong>:</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="f9a71e4f5b2749008d97b5f260b314f5"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/fraddy-oliveira/f9a71e4f5b2749008d97b5f260b314f5" class="embed-card">https://gist.github.com/fraddy-oliveira/f9a71e4f5b2749008d97b5f260b314f5</a></div><p> </p>
<p><strong>Let’s analyze</strong> the example:</p>
<ul>
<li><p>The <code>onLoad</code> function returns a promise.</p>
</li>
<li><p>In the executor function, the resolution function <code>resolve</code> is assigned to <code>window.onload</code>.</p>
</li>
<li><p>Here, <code>window.onload</code> and <code>resolve</code> refer to the same function.</p>
</li>
<li><p>When the <code>load</code> event triggers, the resolution function will execute.</p>
</li>
<li><p>Now, the <code>then</code> callback will execute. The <code>then</code> callback should contain the code that runs after the browser loads.</p>
</li>
</ul>
<h3 id="heading-2-util-library"><strong>2) Util library</strong></h3>
<p>This approach is specific to the Node environment. The <code>util</code> library is stable and built into Node, providing a method to convert callbacks to promises.</p>
<p>Consider an example based on the <code>readFile</code> method of the NodeJs <code>fs</code> module.</p>
<p><strong>Example Prerequisite:</strong></p>
<ul>
<li><p>Create a data file to be read, located in the same directory as the executable file.</p>
</li>
<li><p>Name the data file <code>student_marks.txt</code>.</p>
</li>
</ul>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="f3633fa7ce0f8adbc2c1cd8fa3e45437"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/fraddy-oliveira/f3633fa7ce0f8adbc2c1cd8fa3e45437" class="embed-card">https://gist.github.com/fraddy-oliveira/f3633fa7ce0f8adbc2c1cd8fa3e45437</a></div><p> </p>
<p><strong>Let’s analyze</strong> the example:</p>
<ul>
<li><p>The method <code>fs.readFile</code> is asynchronous and accepts a callback as the last parameter.</p>
</li>
<li><p>The <code>callback</code> format requires two parameters: the first is an <code>error</code> parameter, and the second is the data returned by the method.</p>
</li>
<li><p>Using <code>util.promisify(fs.readFile)</code>, a new function is created from the <code>fs.readFile</code> method. This new function returns a promise.</p>
</li>
<li><p>In the example above, the <code>readFileAsync</code> function returns a promise.</p>
</li>
</ul>
<p><strong>Things to note</strong> about <code>util.promisify</code>:</p>
<ul>
<li><p>The function to be converted must accept a <strong>callback function as the last parameter</strong>.</p>
</li>
<li><p>The callback function should <strong>accept only two parameters</strong>.</p>
</li>
<li><p>The first parameter of the callback must be an <code>error</code> object, and the second parameter should be the <code>return</code> value of the function.</p>
</li>
</ul>
<h3 id="heading-3-generic-approach"><strong>3) Generic approach</strong></h3>
<p>In some scenarios, the callback can accept more than two parameters. For example, the first is the error parameter, and the second and third can be results. In that case, the <code>util.promisify</code> library cannot be used. As a workaround, we will use a function named <code>promisify</code>.</p>
<p><code>promisify</code> is a custom function that is well-tested and supports error handling. It converts callbacks to promises and can be used in both Node.js and browsers.</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="bb75671a1566171a20421e4f3fccb82d"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/fraddy-oliveira/bb75671a1566171a20421e4f3fccb82d" class="embed-card">https://gist.github.com/fraddy-oliveira/bb75671a1566171a20421e4f3fccb82d</a></div><p> </p>
<p><strong>Let’s analyze</strong> <code>promisify</code>:</p>
<ul>
<li><p>Accepts 2 arguments.</p>
</li>
<li><p>The first argument, <code>func</code>, must be a callback-based function.</p>
</li>
<li><p>The second argument is <code>thisArg</code>, which is the execution context of <code>func</code>. The default value is <code>null</code>.</p>
</li>
<li><p>The return value of <code>promisify</code> is a function that, when called, returns a <code>Promise</code>.</p>
</li>
<li><p>Check the example below for the usage of <code>promisify</code>.</p>
</li>
</ul>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="36386a2c08c9497f21e94a6bad3ddd13"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/fraddy-oliveira/36386a2c08c9497f21e94a6bad3ddd13" class="embed-card">https://gist.github.com/fraddy-oliveira/36386a2c08c9497f21e94a6bad3ddd13</a></div><p> </p>
<p>Below is another example which <code>promisify</code> Node.js <code>fs.readFile</code> function.</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="560151b6644e0c6dc6502fe2348476df"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/fraddy-oliveira/560151b6644e0c6dc6502fe2348476df" class="embed-card">https://gist.github.com/fraddy-oliveira/560151b6644e0c6dc6502fe2348476df</a></div><p> </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In addition to the methods discussed in this article, there are alternative approaches, such as utilizing <strong>third-party libraries</strong>. One notable library is <a target="_blank" href="http://bluebirdjs.com/">Bluebird JS</a>.</p>
<p>Thank you for reading. Your feedback on the content of this article is appreciated.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding JavaScript Promises]]></title><description><![CDATA[Introduction
Before promises, we used callback functions to handle asynchronous operations. Asynchronous operations can include fetching data from an API, reading a file, or using a timer (setTimeout). However, callbacks have limitations. Promises ov...]]></description><link>https://blog.fraddyoliveira.com/promises-in-javascript-c9764cba4a23</link><guid isPermaLink="true">https://blog.fraddyoliveira.com/promises-in-javascript-c9764cba4a23</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[promises]]></category><category><![CDATA[asynchronous]]></category><category><![CDATA[ES6]]></category><category><![CDATA[error handling]]></category><dc:creator><![CDATA[Fraddy Oliveira]]></dc:creator><pubDate>Thu, 22 Oct 2020 17:09:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717487018082/d16cc1bf-e5ce-489c-a87d-ee386f8ab2a4.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Before <strong>promises</strong>, we used <strong>callback</strong> functions to handle asynchronous operations. Asynchronous operations can include fetching data from an API, reading a file, or using a timer (<code>setTimeout</code>). However, callbacks have limitations. Promises overcomes those limitations.</p>
<p>So, let's understand promises and learn how to use it.</p>
<h2 id="heading-what-is-a-promise-in-javascript">What is a Promise in JavaScript?</h2>
<p><strong>A promise is an object that handles asynchronous operations.</strong> It ensures you will get a single response (either success or error).</p>
<p><mark>A promise can be in one of three states: </mark> <strong><mark>Pending, Fulfilled, or Rejected</mark></strong><mark>.</mark> Throughout its life cycle, a promise begins in the Pending state and then transitions to either the Fulfilled or Rejected state.</p>
<p>The states of a JavaScript Promise are:</p>
<ul>
<li><p><strong>Pending</strong>: When a promise is initialized using the executor function.</p>
</li>
<li><p><strong>Fulfilled</strong>: When an asynchronous operation is successful.</p>
</li>
<li><p><strong>Rejected</strong>: When an error occurs, such as an exception during code execution or a network error.</p>
</li>
</ul>
<h3 id="heading-syntax-of-a-promise"><strong>Syntax of a Promise</strong></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(executor)
  .then(<span class="hljs-function">(<span class="hljs-params">success</span>) =&gt;</span> {
    <span class="hljs-comment">// When task completes.</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-comment">// When some error occurs and task fails.</span>
  });
<span class="hljs-comment">// for details check promise implementation section on this page.</span>
</code></pre>
<p><mark>Once the promise has been Fulfilled or Rejected, it cannot switch to any other state. </mark> When we say that a promise has settled, we mean it has reached either the Fulfilled or Rejected state.</p>
<p>JavaScript does not expose the state of promises directly. Instead, we should treat a promise as a black box. Only the function that creates the promise knows it's state. When the promise settles, it informs us by executing handlers. The handler functions are the success handler and the error handler.</p>
<h2 id="heading-how-to-implement-a-promise-in-javascript">How to implement a Promise in JavaScript?</h2>
<h3 id="heading-1-initialize-a-promise"><strong>1) Initialize a Promise.</strong></h3>
<pre><code class="lang-javascript"><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">// this is the executor function</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    resolve(<span class="hljs-string">"kudos"</span>);
  }, <span class="hljs-number">3000</span>);
});
</code></pre>
<p>The executor function has <code>resolve</code> and <code>reject</code> arguments, which are success and error callbacks. <strong>Whichever argument is called first, the promise settles into that final state.</strong></p>
<p>A promise will be resolved by invoking either the <code>resolve</code> or <code>reject</code> argument. If the operation is successful, call <code>resolve</code> with the result of the operation as the argument; otherwise, call <code>reject</code> with the error object.</p>
<h3 id="heading-2-attach-success-and-error-handler">2) Attach success and error handler.</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// this example is the continuation of step 1.</span>
promise
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) </span>{
    <span class="hljs-comment">// this is success handler</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"promise resolved. "</span> + data);
  })
  .catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-comment">// this is error handler</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"promise rejected with error: "</span> + err);
  });
</code></pre>
<p><strong>In the executor function, the</strong><code>resolve</code><strong>callback indicates success, which triggers the</strong><code>then</code><strong>handler. The execution of the</strong><code>reject</code><strong>callback indicates an error, which will trigger the</strong><code>catch</code><strong>handler.</strong></p>
<p>To reject a promise, replace <code>resolve('kudos')</code> with <code>reject('sad')</code> in the executor function from step 1 <strong>(Initialize a Promise)</strong>. Other reasons for rejection can include a system error or a network error.</p>
<h3 id="heading-3-what-happens-when-promise-settles">3) What happens when promise settles?</h3>
<p>It will either execute a success function <code>then</code> or an error handling function <code>catch</code>.</p>
<p>Promise provides the <code>finally</code> method, which is useful if you need to do some processing or cleanup once the promise is settled.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// this example is the continuation of step 1.</span>
promise
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) </span>{
    <span class="hljs-comment">// this is success handler</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"promise resolved. "</span> + data);
  })
  .catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-comment">// this is error handler</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"promise rejected with error: "</span> + err);
  })
  .finally(<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">"operation complete"</span>);
  });
</code></pre>
<h2 id="heading-alternative-to-implement-a-promise">Alternative to implement a promise</h2>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example shows a alternate way to define promises.</span>

<span class="hljs-keyword">let</span> fetchVehicles = <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">// This is executor function</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    resolve(<span class="hljs-string">"alternative way to define promise"</span>);
  }, <span class="hljs-number">1000</span>);
});

<span class="hljs-keyword">let</span> successHandler = <span class="hljs-function">(<span class="hljs-params">vehicles</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(vehicles);
};

<span class="hljs-keyword">let</span> errorHandler = <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"fetching vehicles failed"</span>);
};

fetchVehicles.then(successHandler, errorHandler);
</code></pre>
<p>The above code represents an alternative way to define promise. <strong>This code differs from the previous implementation only by specifying success handler and error handler to then method.</strong> In the above code <code>errorHandler</code> handles errors thrown by <code>fetchVehicles</code> and <code>errorHandler</code> will not handle any errors thrown in <code>successHandler</code> function.</p>
<p><strong>The downside of this implementation is that if an error is thrown in the success handler, there is no function to handle the error.</strong></p>
<h2 id="heading-browser-support">Browser Support</h2>
<p><strong>Native support for promise in JavaScript is from ECMAScript 2015 ( ES6 ).</strong> To check the browser compatibility for various promise methods across some major browsers then click <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Browser_compatibility">HERE</a>.</p>
<h2 id="heading-benefits-of-using-promises-over-callbacks">Benefits of using promises over callbacks</h2>
<ul>
<li><p>Better management of asynchronous requests.</p>
</li>
<li><p>Improves code readability.</p>
</li>
<li><p>Improves error handling.</p>
</li>
</ul>
<h2 id="heading-warnings-while-implementing-promises">Warnings while implementing promises</h2>
<ul>
<li><p><strong>Error handling</strong><code>catch</code><strong>function is required otherwise promise will fail silently</strong>.</p>
</li>
<li><p>Do not mix traditional callback functions with promises.</p>
</li>
<li><p>Avoid nesting of promises which will make code debugging, review, management a bit difficult. Refer example given below.</p>
</li>
</ul>
<pre><code class="lang-javascript">getMembersFromAPI()
  .then(<span class="hljs-function">(<span class="hljs-params">apiMembers</span>) =&gt;</span>
    getMembersFromDB(apiMembers)
      .then(<span class="hljs-function">(<span class="hljs-params">members</span>) =&gt;</span>
        addBonusToMembers(members).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
          <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"add bonus resolved"</span>);
        })
      )
      .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"add bonus failed: "</span> + err))
  )
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> checkForMembers())
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error occurred: "</span> + err));
</code></pre>
<h2 id="heading-shortcut-to-settle-a-promise">Shortcut to Settle a promise</h2>
<p><code>Promise.resolve()</code> and <code>Promise.reject()</code> are <strong>shortcuts to create an already resolved or rejected promise</strong> respectively.</p>
<p>Try below snippet.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> shortcuts_res = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"passed"</span>);

shortcuts_res
  .then(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Promise is resolved"</span>))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Promise is rejected"</span>));

<span class="hljs-keyword">let</span> shortcuts_rej = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">"failed"</span>);

shortcuts_rej
  .then(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Promise is resolved"</span>))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Promise is rejected"</span>));
</code></pre>
<h2 id="heading-composition-tools">Composition tools</h2>
<p><code>Promise.all()</code> and <code>Promise.race()</code> are two composition tools. With the help of these tools, we can <strong>execute multiple promises in parallel</strong>. Now we will check the implementation of both tools.</p>
<h3 id="heading-1-promiseall">1) Promise.all()</h3>
<p>If there is a case where we need to <strong>fetch data from multiple APIs and process them only if all calls are successful</strong> then <code>Promise.all()</code> is a good option.</p>
<p>Consider the following example.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Below code demonstrate way to execute Promises in parallel.</span>

<span class="hljs-keyword">let</span> promiseA = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"A"</span>);

<span class="hljs-keyword">let</span> promiseB = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"B"</span>);

<span class="hljs-keyword">let</span> promiseC = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">100</span>, <span class="hljs-string">"C"</span>);
});

<span class="hljs-built_in">Promise</span>.all([promiseA, promiseB, promiseC])
  .then(<span class="hljs-function">(<span class="hljs-params">[resultA, resultB, resultC]</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"result for promise "</span> + resultA);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"result for promise "</span> + resultB);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"result for promise "</span> + resultC);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"promise "</span> + err + <span class="hljs-string">" failed."</span>);
  });
</code></pre>
<p>In this example, there is no specific execution order of <code>promiseA</code>, <code>promiseB</code>, <code>promiseC</code> promises. The <code>then</code> handler will be executed only when all promises are resolved or else <code>catch</code> handler will be called. <strong>If any one promise fails then error handler will execute and promise will settle.</strong></p>
<h3 id="heading-2-promiserace">2) Promise.race()</h3>
<p>From the list of asynchronous requests, <strong>if we want the result of the first operation which settles to resolve or reject state</strong> then Promise.race() will do work for us.</p>
<p>Consider the following example.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// From array of Promises, when we want to the promise which settles down to resolve or reject state first than Promise.race() method is there to do work for us.</span>

<span class="hljs-keyword">let</span> promiseA = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">400</span>, <span class="hljs-string">"A"</span>);
});

<span class="hljs-keyword">let</span> promiseB = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">300</span>, <span class="hljs-string">"B"</span>);
});

<span class="hljs-built_in">Promise</span>.race([promiseA, promiseB])
  .then(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Promise "</span> + value + <span class="hljs-string">" is resolved"</span>))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Promise "</span> + err + <span class="hljs-string">" is rejected"</span>));
</code></pre>
<p>Here we are defining two promises <code>promiseA</code> and <code>promiseB</code>. For <code>promiseA</code>, <code>A</code> is argument to resolve callback. For <code>promiseB</code>, <code>B</code> is argument to resolve callback. In this example, <code>promiseB</code> will be resolved first, so then handler will be executed using <code>promiseB</code> result. You can experiment by interchanging settled states.</p>
<h2 id="heading-chaining-of-promises">Chaining of Promises</h2>
<p>A good way to <strong>execute async operations in series is by chaining all operations using promises.</strong> To implement chaining, the <code>then</code> handler should return a promise, which will be handled by subsequent handlers.</p>
<p>To handle errors, we can add a <code>catch</code> at the end after all <code>then</code> handlers, or we can add a <code>catch</code> after each <code>then</code> handler.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> chainA = <span class="hljs-function"><span class="hljs-keyword">function</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"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      resolve(<span class="hljs-string">"chainA"</span>);
    }, <span class="hljs-number">1000</span>);
  });
};
<span class="hljs-keyword">let</span> chainB = <span class="hljs-function"><span class="hljs-keyword">function</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"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      resolve(<span class="hljs-string">"chainB"</span>);
    }, <span class="hljs-number">3000</span>);
  });
};
<span class="hljs-keyword">let</span> chainC = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">"Error in chainC"</span>);
};
chainA()
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-keyword">return</span> chainB();
  })
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-keyword">return</span> chainC();
  })
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"all async request were successful"</span>);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"common error handle"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"all async request were not successful with error "</span> + err);
  });
</code></pre>
<p>The above example demonstrates chaining promises and handling errors with a single catch at the end. It shows how to perform tasks in series, making chaining promises a perfect example. To chain all tasks, each task should return a promise. An error handler function should be defined at the end of the chain to catch any errors that go unnoticed. Check the example and experiment with it.</p>
<p>The example below illustrates how to add a handler for each specific task that fails. Also, check the comments in the code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> chainA = <span class="hljs-function"><span class="hljs-keyword">function</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"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      resolve(<span class="hljs-string">"chainA"</span>);
    }, <span class="hljs-number">1000</span>);
  });
};
<span class="hljs-keyword">let</span> chainB = <span class="hljs-function"><span class="hljs-keyword">function</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"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      reject(<span class="hljs-string">"chainB"</span>);
    }, <span class="hljs-number">3000</span>);
  });
};
<span class="hljs-keyword">let</span> chainC = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">"Error in chainC"</span>);
};
chainA()
  .then(
    <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      <span class="hljs-comment">// success handler for chainA</span>
      <span class="hljs-built_in">console</span>.log(data);
      <span class="hljs-keyword">return</span> chainB().catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
        <span class="hljs-comment">// error handler for chainB</span>
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error in "</span> + err);
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(err);
      });
    },
    <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
      <span class="hljs-comment">// error handler for chainA</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error in "</span> + err);
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(err);
    }
  )
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-comment">// success handler for chainB</span>
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-keyword">return</span> chainC().catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
      <span class="hljs-comment">// error handler for chainC</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error in "</span> + err);
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(err);
    });
  })
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-comment">// success handler for chainC</span>
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"all async request were successful"</span>);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-comment">// common error handler for all tasks</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"all async request were not successful with error "</span> + err);
  });
<span class="hljs-keyword">let</span> chainC = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">"Error in chainC"</span>);
};
chainA()
  .then(
    <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      <span class="hljs-comment">// success handler for chainA</span>
      <span class="hljs-built_in">console</span>.log(data);
      <span class="hljs-keyword">return</span> chainB().catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
        <span class="hljs-comment">// error handler for chainB</span>
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error in "</span> + err);
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(err);
      });
    },
    <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
      <span class="hljs-comment">// error handler for chainA</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error in "</span> + err);
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(err);
    }
  )
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-comment">// success handler for chainB</span>
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-keyword">return</span> chainC().catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
      <span class="hljs-comment">// error handler for chainC</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error in "</span> + err);
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(err);
    });
  })
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-comment">// success handler for chainC</span>
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"all async request were successful"</span>);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-comment">// common error handler for all tasks</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"all async request were not successful with error "</span> + err);
  });
</code></pre>
<h2 id="heading-things-to-note-about-promises">Things to note about Promises</h2>
<p>To reject a promise, we can call the <code>reject</code> function, which is an argument to the executor function, or we can throw an <code>error</code> in the executor function. Whichever method is used first, the promise will settle to that particular value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"calculation error"</span>); <span class="hljs-comment">// throw will reject promise</span>
  reject(<span class="hljs-string">"Reject!"</span>);
});

promise
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value</span>) </span>{
    <span class="hljs-built_in">console</span>.log(value);
  })
  .catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-built_in">console</span>.log(err);
  });
</code></pre>
<p>In the above code example, the promise is going to be rejected by throwing an <code>error</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Promises are the optimal way to manage asynchronous operations. However, <mark>the syntax for handling promises can sometimes be cumbersome. The solution to this is to use the </mark> <code>async</code><mark>/</mark><code>await</code> <mark> syntax</mark>, which is essentially syntactic sugar for Promises.</p>
<p>To enhance the readability of this article, you can comment on the lines that should be highlighted.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise</a></p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises</a></p>
</li>
</ul>
]]></content:encoded></item></channel></rss>