TypeOfNaN

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

Nick Scialli
November 11, 2020

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...
  }
]

If you'd like to support this blog by buying me a coffee I'd really appreciate it!

Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli