我不知道promise.all在promise.all解决方案中是否是一个很好的实践。我没有把握。
我需要从用户数组中获取信息,然后使用这个信息响应,我需要发送消息通知。
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
...
};用Promise.all嵌套来解决这个问题是个好主意吗?
发布于 2018-07-13 00:20:43
虽然这会奏效,但很难理解为什么这是一个比对第一组请求调用then()更好的选择--记住,then()也会返回一个承诺。在我看来,这不仅更短,而且更清晰。很明显,您正在向每个用户发送通知:
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
// ...
});附注:在您的代码中,您需要从map()回调返回一些内容,否则notificationPromises将是一个空值数组:
Promise.all(promises).then(responses =>{
let notificationPromises = responses.map((user)=>{
return sendNotification('message', user.token); //<< add return
});https://stackoverflow.com/questions/51316028
复制相似问题