How to chain asynchronous functions in JavaScript?

JavaScriptis a single-threaded synchronous function that performs operations. It is a timeconsuming operation that blocks other operations of the thread.

We can use the asynchronous programming provided by JavaScript that performs functions without blocking other operations of the thread. This can be done by asynchronous code like promises or async functions (which basically are cleaner promises).

Asynchronous functions are cool but the time of their execution is not certain which might create a problem. Also, it is not easier to track async functions for any potential errors.

In this article, we will be exploring the chaining of asynchronous functions using ES2015+ features like async functions, arrow functions, etc.

Example 1

In the below example we have 3 async functions.

# index.html


   Chaining Async functions
   


   

Welcome To Tutorials Point

   

Output

The above program will produce the result in the console similar to the below screenshot −

Example 2: Using Promise

In the below example, we are using Promise with then() to call async functions in the chain.

# index.html


   Chaining Async functions
   


   

      Welcome To Tutorials Point    

   

Output

The above program will produce the result in the console similar to the below screenshot −

Example 3:Using async | await

In the below example, we are going to use the async and await function which is a better and cleaner way to perform chaining. The await() function works only inside async() function. So we need to wrap it inside a wrapper function.

# index.html


   Chaining Async functions
   


   

      Welcome To Tutorials Point    

   

Output

The above program will produce the result in the console similar to the below screenshot −

Updated on: 2022-04-22T12:54:13+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements