【发布时间】:2016-07-29 01:49:35
【问题描述】:
我在节点 v6.3.0 中有以下代码在运行两个单独的 Promise 的 api 上运行,具体取决于 POST 请求中是否存在参数。
if (paramExists) {
// call database with this query
User.filter(/* do something with param */)
.then(function (user) {
Data.filter(/* same in both conditions */)
.then(function (data) {
// join data and user
res.send(joinedData);
}) // omit catch for clarity
}) // omit catch for clarity
} else {
// call database with this query
User.filter(/* do something with header */)
.then(function (user) {
Data.filter(/* same in both conditions */)
.then(function (data) {
// join data and user
res.send(joinedData);
}) // omit catch for clarity
}) // omit catch for clarity
}
我确信有办法干掉这段代码,以便在两种情况下的第一个承诺都将用户传递给第二个承诺,但我不知道如何。我应该使用生成器,还是有办法通过我没有得到的承诺来做到这一点?
【问题讨论】:
-
你考虑过
Promise.all。它最终看起来像var p1 = User.filter(paramExists ? args1 : args2), p2 = Data.filter(...); Promise.all([p1, p2]).then(function (user, data) { ... }); -
听起来你在问conditions in promise chains?
标签: javascript node.js promise generator