javascript - Promise.all 里面 promise.all 是 Promise 的好习惯吗?
问题描述
我不知道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
用嵌套解决它是个好主意吗?
解决方案
虽然这会起作用,但很难理解为什么这是一个比仅调用then()
第一组请求更好的选择——记住,then()
它也会返回一个 Promise。这对我来说不仅更短,而且更清晰。很明显,您正在向每个用户发送通知:
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()
ps 在您的代码中,您需要从回调中返回一些内容,否则notificationPromises
将是一个空值数组:
Promise.all(promises).then(responses =>{
let notificationPromises = responses.map((user)=>{
return sendNotification('message', user.token); //<< add return
});
推荐阅读
- javascript - 当我运行项目时,我使用本机警告:ViewPager Android 已从 react-native 中提取?
- database - 如何将 MIT App Inventor 中的联系人导入数据库(tinydb 或 firebase)?
- python - 为没有写入权限的用户在网络驱动器上安装 Python
- python - 将列表项附加到字典,Python
- python - 为什么 TensorBoard 显示错误的余弦距离?
- java - 在switch语句的情况下如何使用&&运算符?
- python - Python,Keras - 二进制文本分类器预测结果为值数组而不是单个概率
- r - predict.glm 在返回 NULL 的有效模型上
- c++ - Alias template for multiple types
- react-native - 如何在反应导航中设置计时器?