Asynchronous JavaScript

Asynchronous JavaScript

We take a deep dive into asynchronous and how the JavaScript language uses this code execution paradigm.

In this article, we are going to discuss asynchronous tasks in significant depth. We will be discussing what exactly asynchronous tasks are, what the hack callbacks are, closures, promises, and much more in the context of JavaScript.


Table of Contents

Prerequisites to Understand Asynchronous Concepts

Overview: What Exactly Does it Mean to Perform Tasks Asynchronously?

As Google says, asynchronous is ‘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 third-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.


Callbacks in JavaScript

Callbacks are simply functions in JavaScript which are to be called and then executed after the execution of another function has finished. So how does it happens Actually, in JavaScript, functions are considered objects and, thus, all other objects, even functions, can be sent as arguments to other functions. The most common and generic use case one can think of is the setTimeout() function in JavaScript.

Consider the following example:

 //with customary function signature  
 setTimeout(function() {  
   console.log('hello1');  
 }, 1000);  
 //with arrow function signature  
 setTimeout(() => {  
   console.log('hello2');  
 }, 2000);  

I have used the setTimeout() function by passing a callback function as an argument into it along with the second argument which is simply the number of milliseconds after which our callback function is executed. I have shown two ways of passing a callback function here, one is the more of customary approach and the second one is the arrow function approach which is more modern.


Sending HTTP Requests in JavaScript

Suppose I want to send an HTTP request to an API which fetches some random text for me. We won’t be digging much into the details of sending HTTP requests, as this is out of the scope of this article.

Now, to hit that API, you need to create two files:

 <!DOCTYPE html>  
 <html>  
   <head></head>  
   <body>  
     <script src="app.js"></script>  
   </body>  
 </html>  
 const puzzleAPIhit = () => {  
   const request = new XMLHttpRequest()  
   request.addEventListener('readystatechange', (e) => {  
     if (e.target.readyState === 4 && e.target.status === 200) {  
       const data = JSON.parse(e.target.responseText);  
       console.log(data.puzzle)  
     } else if (e.target.readyState === 4) {  
       console.log('An error has taken place')  
     }  
   })  
   request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')  
   request.send()  
 }  
 puzzleAPIhit();  

Now, when you open the “index.html” file in your browser, you can see a random string getting printed in the console.


Callback Abstraction

Now, what if we have a complex application that was built over this and thus the logic to generate a random string is something which we should keep hidden or abstract from “users.” To understand this, we can create three files:

 <!DOCTYPE html>  
 <html>  
   <body>  
     <script src="makerequest.js"></script>  
     <script src="app.js"></script>  
   </body>  
 </html>  
 const puzzleAPIhit = () => {  
   return 'some random string';  
 }  
 const myPuzzle = puzzleAPIhit();  
 console.log(myPuzzle);  

Now, we need to replace the actual logic of finding the random string with the hardcoded return statement in thepuzzleAPIhit() function. But as the sending of an HTTP request is asynchronous innature, we can’t simply do this (changing the content of makerequest.js and keeping the other two files intact):

 const puzzleAPIhit = () => {  
   const request = new XMLHttpRequest()  
   request.addEventListener('readystatechange', (e) => {  
     if (e.target.readyState === 4 && e.target.status === 200) {  
       const data = JSON.parse(e.target.responseText);  
       console.log(data.puzzle)  
       return data.puzzle;   
       /*  
         This is absolutely impossible the request.open() is   
         asynchronous in nature.  
       */  
     } else if (e.target.readyState === 4) {  
       console.log('An error has taken place')  
     }  
   })  
   request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')  
   request.send()  
 }  

Because in the console, it would be printing:

 undefined  
 Reliable Public Transportation //A random string  

This is happening because, as request.open()is asynchronous in nature, inside app.js, this is what happens:

The solution? Use callbacks. Here’s what we can do:

 const myPuzzle = puzzleAPIhit((error, puzzle) => {  
   if(error) {  
     console.log(`Error: ${error}`)  
   } else {  
     console.log(puzzle)  
   }  
 });  

 const puzzleAPIhit = (callback) => {  
   const request = new XMLHttpRequest()  
   request.addEventListener('readystatechange', (e) => {  
     if (e.target.readyState === 4 && e.target.status === 200) {  
       const data = JSON.parse(e.target.responseText)  
       callback(undefined, data.puzzle)  
     } else if (e.target.readyState === 4) {  
       callback('An error has taken place', undefined)  
     }  
   })  
   request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')  
   request.send()  
 }  

What have we done? We have just replaced the synchronous call with an asynchronous one by sending the callback in puzzleAPIhit() as an argument. And, in the method  puzzleAPIhit() itself, we called the callback after we got our results, which validates the basic definition of callbacks.


Closures

A closure is a function that has access to the variables defined in outer (and enclosing) functions. As far as scope is concerned, the closure has access to global variables, its own variables, and variables of outer (and enclosing) functions.

Consider the two simple examples of closures below:

 //////////////////////////Example 1://////////////////////////  
 const myFunction = () => {  
   const message = 'My New Message';  
   const printMessage = () => {  
     console.log(message);  
   }  
   printMessage();  
 }  
 myFunction();  
 //////////////////////////Example 2://////////////////////////  
 const myFunctionTwo = () => {  
   const message = 'My New Message Two';  
   const printMessage = () => {  
     console.log(message);  
   }  
   return printMessage;  
 }  
 const myPrintMessage = myFunctionTwo();  
 myPrintMessage();  

It produces the following output:

 My New Message  
 My New Message Two  

From example two, one can see that the closure has access to the message variable even after the function myFunctionTwo() completed its execution, and that’s the great advantage of using closures.


Method Currying

When a function, instead of taking all the arguments at once, takes only one argument and returns a function which will then take the rest of the arguments, this process is known as method currying.

For example:

 /*  
   We have a function adderFunction which returns another function.  
   That return function in turn returns the sum.  
  */  
 const adderFunction = (a) => {  
   return (b) => {  
     return a + b;  
   }  
 }  
 const addToTen = adderFunction(10);  
 console.log(addToTen(12));  
 console.log(addToTen(-1));  
 const addToThousand = adderFunction(1000);  
 console.log(addToTen(18));  
 console.log(addToTen(121));  

Which produces the following output:

 22  
 9  
 28  
 131  

As can be easily seen, now we don’t have to call the function each time with all its arguments, i.e, Method Currying helps in avoiding the need of passing a variable again and again. It also facilitates the reuse of our code.


Promises

Promises are 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 the method defined over the 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 by 2; unless the input type is a number, it will 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 you can see, it is getting messier as it grows. 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 — 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 the simple Promise approach as compared to the 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 was 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.

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

The fetch API simply returns a Promise and hence we can implement handlers to process the response from the Promise. Based on whether the Promise resolves or rejects, we can handle that with JavaScript’s then() method.

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 await operator. When we use them together we get a new way to structure and work with Promises that makes our code a whole lot easier to work with. So, what do 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 the 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 the await operator, let us suppose we have an async function, processData(), that calls a function, getDataPromise(), which, in turn, returns a promise. Now, we want to parse/use the returned data. Let’s look at how we would solve the problem without the 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’re implementing the same logic with the await keyword so that we can compare and contrast the two methods. Actually, the await keyword 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 await 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 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 is rejected.

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.

Feel free to leave any comment or questions. Thanks!


Learn More

Full Stack Developers: Everything You Need to Know

ES5 to ESNext — here’s every feature added to JavaScript since 2015

12 Concepts That Will Level Up Your JavaScript Skills

Vuejs 2 Authentication Tutorial

4 Uses of JavaScript’s Array.map() You Should Know

JavaScript Functional Programming Explained: Fusion & Transduction

Modern JavaScript Explained For Dinosaurs

Learn ReactJS with Webpack 4, Babel 7, and Material Design

The Complete JavaScript Course 2019: Build Real Projects!

JavaScript Bootcamp - Build Real World Applications

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

Originally published by Ayush Jain at https://dzone.com