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.
I have created a set of resources for learning asynchronous JavaScript. These guides—Callbacks, Promises, and Async/Await —cover everything I’ve learned from years of real-world JavaScript experience.
If you found this article helpful, you’ll get so much out of these guides. Each one is optimized for those “lightbulb moments,” building a strong mental model for how asynchronous JavaScript works and how you can use it to create fast, dynamic applications.