Justin
Justin

Reputation: 2049

Synchronously chain BlueBird promises together within an array

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

Upvotes: 2

Views: 1164

Answers (2)

jib
jib

Reputation: 42450

You're chaining asynchronous functions. Think of promises more as return values, not that exciting.

You could put the functions in an array like this, then filter the array:

[funcA, funcB, funcC]
  .filter(somefilter)
  .reduce((p, func) => p.then(int => func(int)), Promise.resolve(1))
  .catch(e => console.error(e));

Or if you're just looking for a better way to write with conditions in a sequence, you might do this:

funcA(1)
  .then(int => condition ? funcB(int) : int)
  .then(funcC);
  .catch(e => console.error(e));

And if you're using ES7 you can use async functions:

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

Upvotes: 1

Justin
Justin

Reputation: 2049

I found a good related thread here. Using the same logic, I was able to get this working:

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

Same results as posted in my original thread

Upvotes: 0

Related Questions