【发布时间】:2018-12-11 12:58:05
【问题描述】:
我的代码中有一个如下所示的承诺链:
myPromise()
.then(getStuffFromDb)
.then(manipulateResultSet)
.then(manipulateWithAsync)
.then(returnStuffToCaller)
现在,在我的 manipulateWithAsync 中,我试图通过再次调用数据库来增强我的结果集,但它没有按我预期的那样工作,因为在调试时我发现控件移动到下一个returnStuffToCaller
的函数下面是我的 manipulateWithAsync 函数的一个想法:
function manipulateWithAsync(rs) {
return rs.map( async function whoCares(singleRecord) {
let smthUseful = await getMoreData(singleRecord.someField);
singleRecord.enhancedField = smthUseful;
return singleRecord;
})
}
我明白这种行为的重点:map 函数确实按预期工作,并且 promise 链不会对此表示怀疑,因为它不能与 awaits 一起使用。 有没有办法让我的 returnStuffToCaller 函数等到异步函数完成他的工作?
我也使用 bluebird,我尝试使用 coo-routine,所以如果你认为这是一个很好的解决方案,我会发布我的 bluebird coo-routine 失败代码:)
谢谢!
【问题讨论】:
-
return Promise.all(rs.map(...))但它可能有助于return映射函数中的某些内容,否则您将使用填充有undefined的数组来解析 -
是的,我显然在我的地图中返回了一些东西。我在创建帖子时即时编写了代码,感谢您指出,马上编辑
-
但是正如@PatrickRoberts 指出的那样,你需要有
Promise.all,否则promise 会使用manipulateWithAsync返回的数组来解析。 -
确认,刚刚修改了我的代码,它工作正常。 @Patrick 如果您可以创建一个答案,我很乐意批准它。
标签: javascript node.js promise async-await bluebird