[英]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. 我不知道一个promise.all
内部promise.all
解决方案是否是一个好习惯。 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? 用Promise.all
嵌套解决它是一个好主意吗?
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. 尽管这行得通,但很难看出为什么这比仅对第一组请求调用then()
更好的选择-请记住, then()
还会返回一个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
// ...
});
ps in your code, you need to return something from the map()
callback otherwise notificationPromises
will be an array of empty values: ps在您的代码中,您需要从map()
回调返回一些内容,否则notificationPromises
将是一个空值数组:
Promise.all(promises).then(responses =>{
let notificationPromises = responses.map((user)=>{
return sendNotification('message', user.token); //<< add return
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.