I'm trying to have a series of promises executed synchronously, chaining them together, but only having certain promises added based on a condition..
Heres an example of what I mean:
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))
If the boolean is true, then the output is: RESULT: 4
, if its false, then its RESULT: 3
, which is exactly what I'm trying to accomplish.
I figured there should be a better, cleaner way to do this though. I'm using the Bluebird promise library, which is pretty powerful. I tried using Promise.join
, which didn't yield the desired result, and neither did Promise.reduce
(But I may have been doing that one incorrectly)
Thanks