将BlueBird同步链接在一个数组中

我试图让一系列的同步执行的承诺,链接在一起,但只有基于条件添加某些承诺。

下面是我的意思的例子:

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)) 

如果布尔值为true,那么输出是: RESULT: 4 ,如果它是false,那么它的RESULT: 3 ,这正是我想要完成的。

我觉得应该有一个更好,更干净的方法来做到这一点。 我正在使用蓝鸟承诺库,这是非常强大的。 我尝试使用Promise.join ,这并没有产生预期的结果,也没有Promise.reduce (但我可能一直在做一个不正确的)

谢谢

你正在链接asynchronousfunction 。 把承诺看作是回报价值,而不是那么激动人心。

你可以把这些函数放在这样的数组中,然后过滤数组:

 [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,则可以使用asynchronousfunction:

 async function foo() { var int = await funcA(1); if (condition) { int = await funcB(int); } return await funcC(int); } 

我在这里find了一个好的相关线程。 使用相同的逻辑,我能够得到这个工作:

 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) ) const toExecute = [funcA, funcB] if( !!condition ) toExecute.push( funcC ) Promise.reduce( toExecute, ( result, currentFunction ) => currentFunction(result), 1) .then( transformedData => console.log('Result:', transformedData) ) .catch( err => console.error('ERROR:', err) ) 

相同的结果发布在我原来的线程