Blog>
Snippets

Handling Multiple Async Operations with Promise.all

Use Promise.all to handle the results of multiple asynchronous operations concurrently without blocking the event loop.
// Function that returns a promise that resolves after a given time
function waitFor(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// Example async operations returning promises
let asyncOperation1 = waitFor(1000).then(() => 'Result of operation 1');
let asyncOperation2 = waitFor(2000).then(() => 'Result of operation 2');
let asyncOperation3 = waitFor(3000).then(() => 'Result of operation 3');

// Use Promise.all to handle multiple promises concurrently
Promise.all([asyncOperation1, asyncOperation2, asyncOperation3])
  .then(results => {
    // Logging results when all promises are resolved
    console.log('All operations completed:', results);
  })
  .catch(error => {
    // Handling error if any of the promises fail
    console.error('An operation failed:', error);
  });
This code block creates three asynchronous operations simulated by the waitFor function that resolves after different times. Promise.all is used to execute the operations concurrently and waits for all of them to complete. Once all promises resolve, it logs the results to the console. If any promise rejects, it catches and logs the error.