how to call multiple functions with async await

Calling Multiple Functions with Async Await

As a web developer, I often come across situations where I need to call multiple functions asynchronously. In such cases, I use async/await to make my code more readable and maintainable.

What is async/await?

Async/await is a feature in JavaScript that allows us to write asynchronous code in a synchronous way. It makes our code easier to read and understand by removing the need for nested callbacks or chain of promises.

How to call multiple functions with async/await?

We can call multiple functions with async/await by using the Promise.all() method. The Promise.all() method takes an array of promises and returns a new promise that resolves when all the promises in the array have resolved.


async function callMultipleFunctions() {
   const [result1, result2, result3] = await Promise.all([function1(), function2(), function3()]);
   console.log(result1);
   console.log(result2);
   console.log(result3);
}

In the above code, we have defined an async function called callMultipleFunctions(). Within this function, we are calling three different functions asynchronously using the Promise.all() method. These functions will execute concurrently, and the Promise.all() method will wait for all of them to complete before returning their results to the array [result1, result2, result3].

We can then use these results as per our requirements. In this example, we are just logging them to the console.

Other ways to call multiple functions with async/await

Another way to call multiple functions with async/await is by using the for...of loop. This method is useful when you have an array of functions that you want to call asynchronously.


async function callMultipleFunctions() {
   const functionsArray = [function1, function2, function3];
   for(const fn of functionsArray) {
      const result = await fn();
      console.log(result);
   }
}

In this example, we are defining an array called functionsArray that contains three different functions. We are then using a for...of loop to iterate over each function and call it asynchronously using await.

Each function will execute one after another, and the results will be logged to the console.

Conclusion

In conclusion, async/await is a powerful feature in JavaScript that allows us to write asynchronous code in a synchronous way. When we need to call multiple functions asynchronously, we can use the Promise.all() method or the for...of loop. Both methods are efficient and easy to use, and it all depends on the situation which one to use.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe