【发布时间】:2019-09-28 05:21:26
【问题描述】:
在下面的代码中,我为每个异步函数使用了await Promise.all,然后最终返回一个值。所以我想问一下:是否有必要为每个异步函数使用await Promise.all,还是一个等待(放在最后)await Promise.all 来完成这项工作?
async sendEmailNotifications() {
const users = await User.find({ })
const promises = users.map(async(user) => {
const _promises = user.appId.map(async(app) => {
const myApp = await App.findOne({ _id: app })
if (myApp) {
const sendNotification = await emailService.analyticsNotification(emailObj)
}
})
await Promise.all(_promises)
})
await Promise.all(promises)
return 'done'
}
【问题讨论】:
-
您没有在 .map 函数中返回任何内容。
-
@AshishKumar 我不想从
.map返回任何东西。我只想等到我的地图功能完成。 -
@AshishKumar
.map在这里很有用,因为他使用异步函数,自动返回 Promises,他想等待所有 Promises 完成。 -
如果您感兴趣的是所有承诺是否已完成,答案是否定的,您可以只使用一个
Promise.all,查看您的代码我看不到内部循环中将返回的任何内容外部的任何东西,所以等待内部的Promise.all不会得到任何东西。但是说到这里,我认为无论如何使用 2 可能会更好,这取决于每个map中有多少,因为一个Promise.all中的太多可能会导致抖动,这是一个并发映射会更好。您的 2 promise.all 在这里可能仍然存在抖动问题,也许外部可能会更好作为for of
标签: javascript node.js asynchronous promise