Promises in Javascript - Series 1: Promise.all

This is a part of our Promises in Javascript Series. If you want to follow up from the beginning you can find the first post here introducing promises.

In this article, we’ll focus on Promise.all. We’ll learn how to use Promise.all to write cleaner asynchronous Javascript code.

Let’s assume you were given an assignment to get the Github Profile Information of all the employees in your organization. Everyone was asked to provide their GitHub username.

As a smart engineer, the first thing I guess you’ll do is to check if Github has an API that does this, right? Gotcha 😁

And yea, they do.

There we go.

So, first of all, if we were going to get the employee profile manually, we’ll go through the list of employees that were provided, pick each of them and check them out on Github.

So, let’s automated that process. Make a list/array of employees, loop through the array, pick each employee’s username and make a http call to the Github users API https://api.github.com/users/${employee} this call will be an async call, so, we’ll add async to the function.

Each user profile will be returned and we can do whatever we want with it, right?

Let’s see how this looks in code:

const getEmployeeProfiles = (employees)=>{
       const info = employees.map(async(employee)=>{
        const userInfo = await axios(https://api.github.com/users/${employee});
        return userInfo.data;
      })
      return info;
}
let employees = ["ezesundayeze", "rexeze", "bmizerany"];
getEmployeeProfiles(employees)

Guess what the getEmployeeProfiles function will come back with, just try! 👶

So, I think most people will think this will return all the user profiles but not exactly. It’ll return an array of promises instead.

Something like this:

[ Promise {  }, Promise {  }, Promise { <
pending> } ]

That’s because each call to the Github user API with axios was a promise and none of them have been resolved yet.

So, how are you going to resolve all of these promises to get the result you want all at once, you asked?

Promise.all to the rescue.

Since Promise.all takes in an array of promises and ensures that they are all resolved or one is rejected before returning a result — that means if one of the calls is rejected everything will fail and it will return undefined and the reason for the rejection in the .catch block.

Here is how that looks in code:

const getEmployeeProfiles = (employees)=>{
       const info = employees.map(async(employee)=>{
        const userInfo = await axios(https://api.github.com/users/${employee});
        return userInfo.data;
     })
      return Promise.all(info)// an array of promises
}

let employees = ["ezesundayeze", "rexeze", "bmizerany"];
getEmployeeProfiles(employees)

That’s it.

The next thing to do is to chain the .then and .catch callbacks to get the resolved result or an error object.

const getEmployeeProfiles = (employees)=>{
       const info = employees.map(async(employee)=>{
        const userInfo = await axios(https://api.github.com/users/${employee});
        return userInfo.data;
     })
      return Promise.all(info)// an array of promises
}

let employees = ["ezesundayeze", "rexeze", "bmizerany"];
getEmployeeProfiles(employees)
  .then((result)=>{
    console.log(result)// this will resturn an array of user profiles if none of the promises was rejected.
  })
  .catch((error)=>{
    consoe.log(error.message)// this will return an error if one of the promises was reject.
  })

There you have it. Let’s say one of the usernames does not exist in the API and we get a 404 error back, everything will fail and we’ll only be left with the error message.

One reason you might want to use the Promise.all API is if all the asynchronous calls you are making are dependent on each other.

On the other hand, if they are not dependent on each other and you want to get the result of each promise you can use Promise.allSettled(), you’ll get the status of each promise and the value it returns as well.

The next topic in this series is the Promise.race

Cheers,

Got questions? You can ask in the comment.

Stay safe.

Categories: Software

1 Comment

Promises in Javascript - Series 1: Promise.race - Eze Sunday Eze · August 8, 2020 at 10:13 pm

[…] is a part of The Promises in Javascript series. In the last part of the series we discussed Promise.all, today we’ll talk about Promise.race and […]

Leave a Reply

Your email address will not be published. Required fields are marked *