How to run a function after two async functions complete - JavaScript


Suppose we have an array of two elements with both of its elements being two asynchronous functions. We are required to do some work, say print something to the console (for the purpose of this question) when the execution of both the async function completes.

How can we approach this challenge?

There are basically two ways to perform some task upon completion of some asynchronous task −

  • Using promises
  • Using async/await functions

But when the code includes dealing with many (more than one) asynchronous functions then the Promise.all function of the former has an edge over the latter.

Example

Following is the code −

const arr = [
   new Promise((resolve, reject) => {
      setTimeout(() => {
         resolve('func1 fired!');
      }, 2000);
   }),
   new Promise((resolve, reject) => {
      setTimeout(() => {
         resolve('func2 fired');
      }, 3000);
   })
];
const lastFunction = () => {
   console.log('this function should be fired at the very last');
};
Promise.all([arr[0], arr[1]]).then((resp) => {
   console.log(resp);
   lastFunction();
}).catch((err) => {
   console.log('something unexpected happened');
})

Output

This will produce the following output in console −

[ 'func1 fired!', 'func2 fired' ]
this function should be fired at the very last

Updated on: 18-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements