Promises in Javascript
Tags: asynchronous, javascript, promises
Published: 2019-05-16 04:54:28

---
title: Promises in Javascript
published: true
description: Promises in Javascript
tags: Asynchronous , Javascript, Promises
---
<div id="toc_container" style="border: 1px solid #aaa;">
<div class="toc_title" style="font-weight: 700; margin: 0; padding: 10px; text-align: center;">
Table of Contents</div>
<ul class="toc_list">
<li><a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html#Prerequisites">1. Prerequisites</a></li>
<li><a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html#Overview">2. Overview</a></li>
</li>
<li><a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html#Promises">3. Promises</a>
<ul>
<li><a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html#ShortHandSyntaxForPromises">Short-Hand Syntax for Promises</a></li>
<li><a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html#PromiseChaining">Promise Chaining</a></li>
<li><a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html#FetchAPI">Fetch API</a></li>
<li><a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html#AsyncAwait">Async-Await</a></li>
</ul>
</li>
</ul>
</div>

<br /><br />
  
<h2 id="Prerequisites">Prerequisites to understand Asynchronous Concepts:</u></h2>
<ul>
<li>Sound Understanding of <a href="https://fullstackgeek.blogspot.com/2019/02/var-vs-let-javascript.html" target="_blank">Declaration of Variables</a> </li>
<li><a href="https://fullstackgeek.blogspot.com/2019/01/variables-scope-in-javascript.html" target="_blank">Scoping of Variables in Javascript</a></li>
</ul>
<h2 id="Overview">
Overview: What exactly is Performing Tasks Asynchronously?</h2>
<div>
As Google says, <b>Asynchronous is what&nbsp;not existing or occurring at the same time.&nbsp;</b>When we execute something synchronously we start some sort of task like fetching a weather report from some 3rd party server and then we have to wait for it to finish before we move on to the next thing. When we execute something asynchronously <i>we can start some task then we can actually get other work done before the task completes, </i>and that's the beauty of performing tasks asynchronously.<i>&nbsp;</i><br />

<h2 id="Promises">
Promises:</h2>

<a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html">Promises</a> are nothing but a much more improvised approach of handling and structuring asynchronous code in comparison to doing the same with callbacks. To prove this we are going to compare and contrast Promises with Callbacks within the same code snippet. To simulate the delay, instead of calling a third-party API, we would be using the setTimeout() method just to make things a little simpler.

The Promise receives two Callbacks in constructor function:&nbsp; <b>resolve</b> and <b>reject. Thes</b>e callbacks inside promises provide us with fine-grained control over error handling and success cases. The resolve callback is used when the execution of promise&nbsp;performed successfully and the reject callback is used to handle the error cases.<br />
When calling the promise, we have <b>then </b>method&nbsp;defined over promise object which can be used to receive the data from promises accordingly.

<span style="font-family: monospace;">Consider the following Code Snippet:</span>

<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> //Example of Callback  
 const getDataCallback = (callback) =&gt; {  
   setTimeout(() =&gt; {  
     const temp = Math.floor(Math.random()*10 + 1);//Generates a random value [1, 10]  
     (temp &lt;= 5)   
       ? callback(undefined, 'This is the Callback data')   
       : callback('This is the Callback error', undefined);    
   }, 10);  
 };  
 getDataCallback((error, data) =&gt; {  
   if(error) {  
     console.log(error);  
   } else {  
     console.log(data);  
   }  
 });  
 //Example of Promise  
 const myPromise = new Promise((resolve, reject) =&gt; {  
   setTimeout(() =&gt; {  
     const temp = Math.floor(Math.random()*10 + 1);//Generates a random value [1, 10]  
     (temp &lt;= 5)   
       ? resolve('This is the Promise data')   
       : reject('This is the Promise error');    
   }, 10);  
 });  
 myPromise.then((data) =&gt; {  
   console.log(data);  
 }, (error) =&gt; {  
   console.log(error);  
 });  
</code></pre>

<span style="font-family: monospace;">It produces the following output:</span>

<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> This is the Callback data  
 This is the Promise error  
</code></pre>

<h3 id="ShortHandSyntaxForPromises">
<u>Short-Hand Syntax for Promises:</u></h3>
Suppose we have a function which accepts some integer and returns a promise based on some complex calculations (which, however, we will be simulating with setTimeout()). Actually, there is nothing special in <a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html">Short-Hand Syntax</a> except it provides a concise way of returning objects, variables or even promises from functions (functions using arrow syntax).
<span style="font-family: monospace;">Consider the following Code Snippet:</span>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> //Example of a function returning a Promise  
 const getDataFromPromise = (data) =&gt; {  
   return new Promise((resolve, reject) =&gt; {  
     setTimeout(() =&gt; {  
       (data &lt;= 5)   
         ? resolve('This is the Promise data')   
         : reject('This is the Promise error');    
     }, 1000);  
   });  
 }    
 //Example of a function returning a Promise using Short-Hand syntax  
 const getDataFromPromiseUsingShortHandSyntax = (data) =&gt; new Promise((resolve, reject) =&gt; {  
   setTimeout(() =&gt; {  
     (data &lt;= 5)   
       ? resolve('This is the Promise data using Short-Hand syntax')   
       : reject('This is the Promise error using Short-Hand syntax');    
   }, 1000);  
 });  
 const myPromiseOne = getDataFromPromise(3);  
 myPromiseOne.then((data) =&gt; {  
   console.log(data);  
 }, (error) =&gt; {  
   console.log(error);  
 });  
 const myPromiseTwo = getDataFromPromiseUsingShortHandSyntax(30);  
 myPromiseTwo.then((data) =&gt; {  
   console.log(data);  
 }, (error) =&gt; {  
   console.log(error);  
 });  
</code></pre>

<span style="font-family: monospace;">It produces the following output:</span>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> This is the Promise data  
 This is the Promise error using Short-Hand syntax  
</code></pre>

<h3 id="PromiseChaining">
<u>Promise Chaining:</u></h3>
<div>
<div>
Suppose we have a function funcA(). Suppose, funcA() returns a number after multiplying the input number with 2 if the input type is number otherwise return an error. And based on the output received from funcA(), we again want to call the same function (i.e, functA()) by passing the output received from the first call as an input.&nbsp;&nbsp;</div>
<div>
<br /></div>
<div>
As we did before, While solving the problem above, we would be contrasting and comparing the Callback approach and Promise approach.</div>
</div>
<span style="font-family: monospace;">Consider the following Code Snippet(Callback Approach):</span>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> //Callback Approach  
 const funcA = (num, callback) =&gt; {  
   setTimeout(() =&gt; {  
     if(typeof num === 'number') {  
       callback(undefined, 2*num);  
     } else {  
       callback('Input type must be number');  
     }  
   }, 2000);  
 }  
 funcA(2, (error, data) =&gt; {  
   if(error) {  
     console.log(error);  
   } else {  
     funcA(data, (error, data) =&gt; {  
       if(error) {  
         console.log(error);  
       } else {  
         console.log('Final Output(Using Callback Approach): ' + data);  
       }  
     });  
   }  
 });  
</code></pre>
As one can easily see and analyze, it is getting messier as it grows. So what we're seeing here is commonly called <b>Callback hell</b>. Yes, there is actually a name for this messier code and obviously, we need a better solution which is both manageable and understandable and <b>Promise Chaining</b> comes to our rescue here.<br />
However, With Promises, We would be seeing two approaches here:
<span style="font-family: monospace;">Consider the following Code Snippet(Promise Approach, without Promise Chaining):</span>

<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> const funcA = (num) =&gt; new Promise((resolve, reject) =&gt; {  
   setTimeout(() =&gt; {  
     (typeof num === 'number')   
       ? resolve(2*num)   
       : reject('Input type must be number');  
   }, 2000);  
 });  
 funcA(2).then((data) =&gt; {  
   funcA(data).then((data) =&gt; {  
     console.log(data);  
   }, (error) =&gt; {  
     console.log(error);  
   });  
 }, (error) =&gt; {  
   console.log(error);  
 });  
</code></pre>
<b><br /></b> Even without Promise Chaining, our code looks far leaner with simple Promise Approach as compared to bare Callback approach. Now, we would be looking a still better approach which uses Promise Chaining. Before moving to the code of Promise Chaining, let us put some light on it theoretically:
<ol style="text-align: left;">
<li>When we return a Promise from another Promise handler (i.e, then()), it is called Promise Chaining.</li>
<li>We can easily attach another <b>then() </b>handler when our Promise resolves (the one we have returned) and this can be done n number of times based on our needs.</li>
<li>We can employ a single error handler called <b>catch() </b>which<b>&nbsp;</b>is attached at the very last of our Promise Chaining.&nbsp;</li>
</ol>
<span style="font-family: monospace;">Consider the following Code Snippet(Promise Approach, with Promise Chaining):</span> 
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> const funcA = (num) =&gt; new Promise((resolve, reject) =&gt; {  
   setTimeout(() =&gt; {  
     (typeof num === 'number')   
       ? resolve(12*num)   
       : reject('Input type must be number');  
   }, 2);  
 });  
 funcA(12).then((data) =&gt; {  
   return funcA(data);  
 }).then((data) =&gt; {  
   console.log(data);  
 }).catch((error) =&gt; {  
   console.log(error);  
 });  
</code></pre>
As<b> </b>one can see, the code is much much cleaner and concise now, thanks to Promise Chaining.
<h3 id="FetchAPI">
<u>Fetch API:</u></h3>
<div>
The Fetch API introduced in relatively newer versions of JavaScript and has built-in support for Promises. Technically, it is just another method of hitting HTTP Requests while harnessing the powers and perks of Promises and Promise Chaining. Previously, we have seen how we can <a href="https://fullstackgeek.blogspot.com/2019/02/asynchronous-javascript-explained-for-beginners.html#HittingHTTPRequests" target="_blank">hit the HTTP Requests</a>&nbsp;in this article.</div>
<div>
<br /></div>
<div>
So in the fetch API, you pass the arguments in the following order:</div>
<div>
<ul style="text-align: left;">
<li>URL</li>
<li>{} (This is purely optional, used to customize our Request)</li>
</ul>
<div>
The fetch API simply returns a Promise and hence we can implement&nbsp;handlers like <b>then </b>to process the response from the promise. Based on the promise <b>resolves or rejects, </b>we can handle that in<b> then().</b>&nbsp;&nbsp;</div>
</div>
<span style="font-family: monospace;">Consider the following Code Snippet:</span>

<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> fetch('http://puzzle.mead.io/puzzle', {}).then((response) =&gt; {  
   if (response.ok) {  
     return response.json();  
     /*  
       Actually, the .json() method takes the response and returns a Promise Object and hence  
       We need to add another then() as we have done in Promise Chaining   
     */  
   } else {  
     throw new Error('Unable to fetch the puzzle');  
   }  
 }).then((data) =&gt; {  
   console.log(data.puzzle);  
 }).catch((error) =&gt; {  
   console.log(error);  
 });  
</code></pre>
<u>Suggested </u>Reading:&nbsp;<a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch" target="_blank">Mozilla-MDN-Fetch</a>
<h3 id="AsyncAwait">
<u>Async-Await:</u></h3>
<div>
We have the async function and the Awake operator. When we use them together we get a new way to structure and work with our promises that makes the code a whole lot easier to work with. So, what Async and Await do? Let's start with Async:</div>

<span style="font-family: monospace;">Consider the following Code Snippet:</span>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> const processData = () =&gt; {  
   return 12;  
 };  
 const processDataAsycn = async () =&gt; {  
   return 12;  
 };  
 console.log('Data from processData() without async: ' + processData() );  
 console.log('Data from processDataAsycn() with async: ' + processDataAsycn() );  
</code></pre>
<div>
<u><br /></u></div>
<span style="font-family: monospace;">It produces the following output:</span>
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> Data from processData() without async: 12  
 Data from processDataAsycn() with async: [object Promise]  
</code></pre>
<div>
<u><br /></u> As you can see, adding <b>async </b>keyword<b> </b>to a function makes it work a bit differently. It starts returning a <b>promise</b>. The promise we get back from an async function gets resolved with whatever value we return from that function. As with any function returning promises, we can handle the response (i.e, promise) from an async function using handlers like <b>catch</b> and <b>then</b>.</div>
<b><br /></b> <span style="font-family: monospace;">Consider the following Code Snippet:</span> <b><br /></b>


<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> const processDataAsycn = async (num) =&gt; {  
   if(typeof num === 'number') {  
     return 2*num;  
   } else {  
     throw new Error('Something went wrong');  
   }  
 };  
 processDataAsycn(21).then((data) =&gt; {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) =&gt; {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });  
</code></pre>
<b><br /></b>Now, moving to <b>await </b>operator<b>, </b>let us suppose we have an <b>async</b> function processData() which calls a function getDataPromise() which in turn returns a promise. Now, we want to parse/use the data returned. Let us see, how we would solve the problem without <b>await</b> operator.
<span style="font-family: monospace;">Consider the following Code Snippet:</span>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> const getDataPromise = (num) =&gt; new Promise((resolve, reject) =&gt; {  
   setTimeout(() =&gt; {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () =&gt; {  
   return getDataPromise(22).then((data) =&gt; {  
     return getDataPromise(data);  
   });  
 };  
 processDataAsycn().then((data) =&gt; {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) =&gt; {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   
</code></pre>
Now, we would be implementing the same logic with the<b> await</b> keyword so that we can compare and contrast the two methods. Actually,&nbsp;The keyword await makes JavaScript wait until that promise settles and returns its result. So, it looks like the code is synchronous but it is indeed Asynchronous.<br />
<br />
<span style="font-family: monospace;">Consider the following Code Snippet:</span>
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> const getDataPromise = (num) =&gt; new Promise((resolve, reject) =&gt; {  
   setTimeout(() =&gt; {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () =&gt; {  
   let data = await getDataPromise(2);  
   data = await getDataPromise(data);  
   return data;  
 };  
 processDataAsycn().then((data) =&gt; {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) =&gt; {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   
</code></pre>
 So with async and the awake operator, we can structure our code that uses promises to look more like regular old synchronous code. We can perform one operation after the other. This other code is never going to run until the previous promise either resolves or rejects the return statement.
Now, in this case, we've only seen the happy path where all of the promises do indeed resolve. Let's go ahead and explore what happens when one of them rejects<br />
<span style="font-family: monospace;">Consider the following Code Snippet:</span>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> const getDataPromise = (num) =&gt; new Promise((resolve, reject) =&gt; {  
   setTimeout(() =&gt; {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () =&gt; {  
   let data = await getDataPromise('2');  
   data = await getDataPromise(data);  
   return data;  
 };  
 processDataAsycn().then((data) =&gt; {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) =&gt; {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   
</code></pre>
<span style="font-family: monospace;">It produces the following output:</span>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: &quot;arial&quot;; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> Error from processDataAsycn() with async( When promise gets rejected ): Input must be an number  
</code></pre>
The <b>awake </b>operator throws the error for us if the promise is rejected. We can see that promise chaining is no longer a daunting thing.<br />


 
<br />
<div>
Liked this blog? Don't miss out on any future blog posts by <a href="https://www.specificfeeds.com/fullstackgeek?subParam=followPub" target="_blank">Subscribing Here</a>
</div>