Executing Multiple Asynchronous Calls Simultaneously with '.then()' Triggered Only After All Complete

You can achieve this by using Promise.all()

Promise.all() takes an array of promises and returns a single promise that resolves when all of the promises in the array have resolved, or rejects when any of the promises reject.

Here's an example of how you can use it:

const asyncCall1 = () => {
  return new Promise((resolve, reject) => {
    // Simulate an asynchronous operation
    setTimeout(() => {
      console.log("Async call 1 complete");
      resolve("Result from async call 1");
    }, 2000);
  });
};

const asyncCall2 = () => {
  return new Promise((resolve, reject) => {
    // Simulate another asynchronous operation
    setTimeout(() => {
      console.log("Async call 2 complete");
      resolve("Result from async call 2");
    }, 3000);
  });
};

// Run both async calls simultaneously
Promise.all([asyncCall1(), asyncCall2()])
  .then(([result1, result2]) => {
    console.log("Both async calls complete");
    console.log("Result from async call 1:", result1);
    console.log("Result from async call 2:", result2);
  })
  .catch((error) => {
    console.error("An error occurred:", error);
  });

In this example, asyncCall1() and asyncCall2() are two asynchronous functions. Promise.all() waits for both of these promises to resolve, and then the .then() block runs with an array containing the results from both async calls.

If any of the promises reject, the .catch() block will handle the error.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda