Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Promise.all output with promises index

I am using nodejs v8+ which supports default async await style of code.

In my problem, I am trying to push all the promises into an array and then use Promise.all to with await keyword to get the responses. But the problem is, I am not able to map the promises with the keys.

Here is the example:

let users = ["user1", "user2", "user3"];

    let promises = [];
    for(let i = 0; i < users.length; i++){
      let response = this.myApiHelper.getUsersData(users[i]);
      promises.push(response);
    }
    let allResponses = await Promise.all(promises);

Here I get all the collected response of all the responses, but I actually want to map this by user. For example currently I am getting data in this format:

[
{
  user1 Data from promise 1
},
{
  user2 Data from promise 2
},
{
  user3 Data from promise 3
}
]

But I want data in this format:

[
 {
  "user1": Data from promise 1
 },
 {
   "user2": Data from promise 2
 },
 {
   "user3": Data from promise 3
 }
]

I am sure there must be a way to map every promise by user, but I am not aware of.

like image 990
undefined Avatar asked Jan 30 '23 05:01

undefined


1 Answers

We gonna create an array of user. Iterate over it to create an array of Promise we give to Promise.all. Then iterate on the answer to create an object that's matching the user with the associated answer from getUsersData.

Something to know about Promise.all is that the order of the returned data depends on the order of the promises given in entry of it.


const users = ['user1', 'user2', 'user3'];

const rets = await Promise.all(users.map(x => this.myApiHelper.getUsersData(x)));

const retWithUser = rets.map((x, xi) => ({
   user: users[xi],
   ret: x,
}));

Here you have a great tutorial about Array methods (map, filter, some...).

like image 94
Orelsanpls Avatar answered Feb 03 '23 22:02

Orelsanpls