Promise.all() with async and await to run in console

Using Promise.all() with async and await to run in console

As a web developer, I have used Promise.all() with async and await to handle multiple asynchronous operations concurrently. This method returns a single Promise that resolves when all the promises in the iterable argument have resolved or rejects with the reason of the first promise that rejects.

Code Example:


async function fetchAllData() {
  const [userData, postsData, commentsData] = await Promise.all([
    fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()),
    fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json()),
    fetch('https://jsonplaceholder.typicode.com/comments').then(res => res.json())
  ]);
  return { userData, postsData, commentsData };
}
fetchAllData().then(data => console.log(data));

In this example, fetchAllData() is an asynchronous function that uses Promise.all() to fetch user data, posts data, and comments data from a dummy REST API endpoint. Since the API requests are made concurrently, the function returns a single Promise that resolves with an object containing all the fetched data.

The code above uses the await keyword to wait for all the API requests to resolve before destructuring the response objects into separate variables. Finally, the function returns an object containing all the fetched data.

You can then use .then() to log the returned data to the console.

Other Ways to Use Promise.all()

You can also use Promise.all() with an array of promises instead of an array of values. Here's an example:


const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(values => {
  console.log(values);
});

In this example, the Promise.all() method is used with an array of promises. The promises resolve to different types of values (an integer, a string, and a Promise), but they all resolve at different times. The code waits for all the promises to resolve before logging an array of their resolved values to the console.

Both of these methods are useful for handling multiple asynchronous operations concurrently and returning a single Promise that resolves with all the data once all the operations are complete.

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