makitocode
makitocode

Reputation: 948

Promise.all inside promise.all its a good practice for Promises?

I don't know if a promise.all inside promise.all solution is a good practice or not. I'm not sure.

I need to get info from array of users, then with this info responses, i need to send message notification.

let userList = ['key1', 'key2', 'key3']; //More data can arrive
let promises = userList.map((userKey,index)=>{
            return GetUserById(db.ref(`Users/${userKey}`));
});

Promise.all(promises).then(responses =>{
  let notificationPromises = responses.map((user)=>{
      sendNotification('message', user.token);
  });
  return Promise.all(notificationPromises)
}).then(()=>{
   //notifications were sent
   ...
};

Is it a good idea to solve it with Promise.all nested?

Upvotes: 0

Views: 56

Answers (1)

Mark
Mark

Reputation: 92461

While this will work, it's hard to see why this is a better choice than just calling then() on the first set of requests -- remember, then() also returns a promise. This seems not only shorter, much clearer to me. It's very obvious that you are sending notifications to each user:

let userList = ['key1', 'key2', 'key3']; //More data can arrive
let promises = userList.map((userKey,index)=>{
            return GetUserById(db.ref(`Users/${userKey}`))
            .then(user => sendNotification('message', user.token) )
});

Promise.all(promises)
.then(()=>{
    //notifications were sent
    // ...
});

p.s. in your code, you need to return something from the map() callback otherwise notificationPromises will be an array of empty values:

Promise.all(promises).then(responses =>{
    let notificationPromises = responses.map((user)=>{
        return sendNotification('message', user.token); //<< add return
    });

Upvotes: 1

Related Questions