我正在尝试同步执行一系列 promise ,将它们链接在一起,但只根据条件添加某些 promise ..
这是我的意思的一个例子:
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))
如果 bool 值为真,则输出为:RESULT: 4
,如果为假,则为 RESULT: 3
,这正是我正在尝试的完成。
不过,我认为应该有更好、更简洁的方法来做到这一点。我正在使用 Bluebird promise 库,它非常强大。我尝试使用 Promise.join
,它没有产生预期的结果,Promise.reduce
也没有(但我可能做错了)
谢谢
最佳答案
您正在链接异步函数。将 promise 更多地视为返回值,而不是那么令人兴奋。
你可以像这样把函数放在一个数组中,然后过滤这个数组:
[funcA, funcB, funcC]
.filter(somefilter)
.reduce((p, func) => p.then(int => func(int)), Promise.resolve(1))
.catch(e => console.error(e));
或者,如果您只是在寻找一种更好的方式来编写序列中的条件,您可以这样做:
funcA(1)
.then(int => condition ? funcB(int) : int)
.then(funcC);
.catch(e => console.error(e));
如果你使用的是 ES7,你可以使用异步函数:
async function foo() {
var int = await funcA(1);
if (condition) {
int = await funcB(int);
}
return await funcC(int);
}
关于javascript - 在数组中将 BlueBird promise 同步链接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35383509/