TypeOfNaN

How to Wait for Multiple Promises to Resolve in JavaScript Using Promise.all

Nick Scialli
November 11, 2020

New — Check out my free newsletter on how the web works!

After getting the hang of async programming in javascript, you might quickly find you need to wait for multiple async tasks to happen. Enter Promise.all!

A Single Promise

To start out, let’s do a simple fetch request that returns a Promise. I’m using the node runtime, so I’ll use the node-fetch package. In this request, we’ll just grab some information about my github profile from the open github api.

const fetch = require('node-fetch');

fetch('https://api.github.com/users/nas5w')
  .then((res) => res.json())
  .then((user) => {
    console.log(user);
  });

And sure enough, we log our user.

{
    login: 'nas5w',
    id: 7538045,
    node_id: 'MDQ6VXNlcjc1MzgwNDU=',
    avatar_url: 'https://avatars2.githubusercontent.com/u/7538045?v=4',
    etc.
}

Multiple Promises

This is good and fine, but what if we want to fetch two different accounts and only take action after both requests are resolved?

This is when we can use Promise.all! Promise.all takes an array of promises and only executes the function provided to then after all promises in the array resolve.

It will look something like this:

Promise.all([promise1, promise2, promise3]).then((data) => {
  // Do something with array of resolved promises
});

In our fetch example, we can fetch details about bothe the nas5w and octocat accounts and log the details only after both promises have resolved:

const fetch = require('node-fetch');

function getAccount(id) {
  return fetch(`https://api.github.com/users/${id}`).then((res) => res.json());
}

const promise1 = getAccount('nas5w');
const promise2 = getAccount('octocat');

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

And now we get an array with information about both users, logged only after both fetch requests are done:

[
  {
    login: 'nas5w',
    id: 7538045,
    node_id: 'MDQ6VXNlcjc1MzgwNDU=',
    avatar_url: 'https://avatars2.githubusercontent.com/u/7538045?v=4',
    etc...
  },
  {
    login: 'octocat',
    id: 583231,
    node_id: 'MDQ6VXNlcjU4MzIzMQ==',
    avatar_url: 'https://avatars3.githubusercontent.com/u/583231?v=4',
    etc...
  }
]

🎓 Learn how the web works

One of the best ways to level up your tech career is to have a great foundational understanding of how the web works. In my free newsletter, How the Web Works, I provide simple, bite-sized explanations for various web topics that can help you boost your knowledge. Join 2,500+ other learners on the newsletter today!

Signing up is free, I never spam, and you can unsubscribe any time. You won't regret it!

Sign up for the newsletter »
Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli