DEV Community

Full Stack Geek
Full Stack Geek

Posted on • Updated on

Promises in Javascript

Table of Contents

Prerequisites to understand Asynchronous Concepts:

Overview: What exactly is Performing Tasks Asynchronously?

As Google says, Asynchronous is what not existing or occurring at the same time. 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 we can start some task then we can actually get other work done before the task completes, and that's the beauty of performing tasks asynchronously. 

Promises:

Promises 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:  resolve and reject. These 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 performed successfully and the reject callback is used to handle the error cases.

When calling the promise, we have then method defined over promise object which can be used to receive the data from promises accordingly.

Consider the following Code Snippet:

 //Example of Callback  
 const getDataCallback = (callback) => {  
   setTimeout(() => {  
     const temp = Math.floor(Math.random()*10 + 1);//Generates a random value [1, 10]  
     (temp <= 5)   
       ? callback(undefined, 'This is the Callback data')   
       : callback('This is the Callback error', undefined);    
   }, 10);  
 };  
 getDataCallback((error, data) => {  
   if(error) {  
     console.log(error);  
   } else {  
     console.log(data);  
   }  
 });  
 //Example of Promise  
 const myPromise = new Promise((resolve, reject) => {  
   setTimeout(() => {  
     const temp = Math.floor(Math.random()*10 + 1);//Generates a random value [1, 10]  
     (temp <= 5)   
       ? resolve('This is the Promise data')   
       : reject('This is the Promise error');    
   }, 10);  
 });  
 myPromise.then((data) => {  
   console.log(data);  
 }, (error) => {  
   console.log(error);  
 });  

It produces the following output:

 This is the Callback data  
 This is the Promise error  

Short-Hand Syntax for Promises:

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 Short-Hand Syntax except it provides a concise way of returning objects, variables or even promises from functions (functions using arrow syntax).
Consider the following Code Snippet:

 //Example of a function returning a Promise  
 const getDataFromPromise = (data) => {  
   return new Promise((resolve, reject) => {  
     setTimeout(() => {  
       (data <= 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) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (data <= 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) => {  
   console.log(data);  
 }, (error) => {  
   console.log(error);  
 });  
 const myPromiseTwo = getDataFromPromiseUsingShortHandSyntax(30);  
 myPromiseTwo.then((data) => {  
   console.log(data);  
 }, (error) => {  
   console.log(error);  
 });  

It produces the following output:

 This is the Promise data  
 This is the Promise error using Short-Hand syntax  

Promise Chaining:

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.  

As we did before, While solving the problem above, we would be contrasting and comparing the Callback approach and Promise approach.

Consider the following Code Snippet(Callback Approach):

 //Callback Approach  
 const funcA = (num, callback) => {  
   setTimeout(() => {  
     if(typeof num === 'number') {  
       callback(undefined, 2*num);  
     } else {  
       callback('Input type must be number');  
     }  
   }, 2000);  
 }  
 funcA(2, (error, data) => {  
   if(error) {  
     console.log(error);  
   } else {  
     funcA(data, (error, data) => {  
       if(error) {  
         console.log(error);  
       } else {  
         console.log('Final Output(Using Callback Approach): ' + data);  
       }  
     });  
   }  
 });  

As one can easily see and analyze, it is getting messier as it grows. So what we're seeing here is commonly called Callback hell. Yes, there is actually a name for this messier code and obviously, we need a better solution which is both manageable and understandable and Promise Chaining comes to our rescue here.

However, With Promises, We would be seeing two approaches here:
Consider the following Code Snippet(Promise Approach, without Promise Chaining):

 const funcA = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number')   
       ? resolve(2*num)   
       : reject('Input type must be number');  
   }, 2000);  
 });  
 funcA(2).then((data) => {  
   funcA(data).then((data) => {  
     console.log(data);  
   }, (error) => {  
     console.log(error);  
   });  
 }, (error) => {  
   console.log(error);  
 });  


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:

  1. When we return a Promise from another Promise handler (i.e, then()), it is called Promise Chaining.
  2. We can easily attach another then() handler when our Promise resolves (the one we have returned) and this can be done n number of times based on our needs.
  3. We can employ a single error handler called catch() which is attached at the very last of our Promise Chaining. 

Consider the following Code Snippet(Promise Approach, with Promise Chaining):

 const funcA = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number')   
       ? resolve(12*num)   
       : reject('Input type must be number');  
   }, 2);  
 });  
 funcA(12).then((data) => {  
   return funcA(data);  
 }).then((data) => {  
   console.log(data);  
 }).catch((error) => {  
   console.log(error);  
 });  

As one can see, the code is much much cleaner and concise now, thanks to Promise Chaining.

Fetch API:

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 hit the HTTP Requests in this article.

So in the fetch API, you pass the arguments in the following order:

  • URL
  • {} (This is purely optional, used to customize our Request)

The fetch API simply returns a Promise and hence we can implement handlers like then to process the response from the promise. Based on the promise resolves or rejects, we can handle that in then().  

Consider the following Code Snippet:

 fetch('http://puzzle.mead.io/puzzle', {}).then((response) => {  
   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) => {  
   console.log(data.puzzle);  
 }).catch((error) => {  
   console.log(error);  
 });  

Suggested Reading: Mozilla-MDN-Fetch

Async-Await:

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:

Consider the following Code Snippet:

 const processData = () => {  
   return 12;  
 };  
 const processDataAsycn = async () => {  
   return 12;  
 };  
 console.log('Data from processData() without async: ' + processData() );  
 console.log('Data from processDataAsycn() with async: ' + processDataAsycn() );  



It produces the following output:

 Data from processData() without async: 12  
 Data from processDataAsycn() with async: [object Promise]  


As you can see, adding async keyword to a function makes it work a bit differently. It starts returning a promise. 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 catch and then.

Consider the following Code Snippet:

 const processDataAsycn = async (num) => {  
   if(typeof num === 'number') {  
     return 2*num;  
   } else {  
     throw new Error('Something went wrong');  
   }  
 };  
 processDataAsycn(21).then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });  


Now, moving to await operator, let us suppose we have an async 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 await operator.
Consider the following Code Snippet:

 const getDataPromise = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () => {  
   return getDataPromise(22).then((data) => {  
     return getDataPromise(data);  
   });  
 };  
 processDataAsycn().then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   

Now, we would be implementing the same logic with the await keyword so that we can compare and contrast the two methods. Actually, 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.



Consider the following Code Snippet:

 const getDataPromise = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () => {  
   let data = await getDataPromise(2);  
   data = await getDataPromise(data);  
   return data;  
 };  
 processDataAsycn().then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   

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

Consider the following Code Snippet:

 const getDataPromise = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () => {  
   let data = await getDataPromise('2');  
   data = await getDataPromise(data);  
   return data;  
 };  
 processDataAsycn().then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   

It produces the following output:

 Error from processDataAsycn() with async( When promise gets rejected ): Input must be an number  

The awake operator throws the error for us if the promise is rejected. We can see that promise chaining is no longer a daunting thing.

Liked this blog? Don't miss out on any future blog posts by Subscribing Here

Top comments (1)

Collapse
 
shoayb_34 profile image
Sho-ayb

This is the best article on Callback, Promises and Async/await approaches I have read so far. I especially appreciate how the article takes you from using callbacks, to resolving the issue that callbacks can produce using Promises and then how Async/await can simplify the code even further. Thanks