【发布时间】:2016-05-24 20:05:04
【问题描述】:
我正在尝试同步执行一系列承诺,将它们链接在一起,但仅根据条件添加某些承诺..
这是我的意思的一个例子:
const Promise = require('bluebird')
const funcA = int => new Promise( res => res(++int) )
const funcB = int => new Promise( res => res(++int) )
const funcC = int => new Promise( res => res(++int) )
let mainPromise = funcA(1)
// Only execute the funcB promise if a condition is true
if( true )
mainPromise = mainPromise.then(funcB)
mainPromise = mainPromise.then(funcC)
mainPromise
.then( result => console.log('RESULT:',result))
.catch( err => console.log('ERROR:',err))
如果布尔值为真,则输出为:RESULT: 4,如果为假,则为RESULT: 3,这正是我想要完成的。
我认为应该有更好、更清洁的方法来做到这一点。我正在使用 Bluebird Promise 库,它非常强大。我尝试使用Promise.join,但没有产生预期的结果,Promise.reduce 也没有(但我可能做错了)
谢谢
【问题讨论】:
-
你能告诉我们你是如何使用
Promise.reduce的吗? -
只是吹毛求疵,但promises are not executed
-
您想评估
funcA()已解决时的条件,还是在构建链时静态已知(如您的示例中)?还是没关系?
标签: javascript node.js promise bluebird es6-promise