lostAstronaut lostAstronaut - 5 months ago 36
Node.js Question

Bluebird promise multi-level

I am struggling to figure out how to have multiple levels of promises execute asynchronously. I have searched through the documentation but most promise libraries have you waiting for all promises to do some logic or one then the next. I need an aspect of both of this. I wrote up a quick demonstration of what i'm trying to achieve.

The general idea behind this is I have 4 functions which I need to call. A & B can be called right away at the same time. C is dependent on B's return. Then I need all three (A,B,C) to compute D. How would I structure this?

I tried to draw the general flow chart here:

A -> -> D
B -> C ->





Sample code:

var bluebird = require('bluebird');

function a(){
setTimeout(function(){
console.log('a called');
return 'a';
},1000);
}

function b(){
setTimeout(function(){
console.log('b called');
return 'b message';
},1000);
}

function c(bMessage){
setTimeout(function(){
console.log('c called');
return 'c set in motion';
},1000);
}

function d(aMessage, bMessage, cMessage){
setTimeout(function(){
console.log('prmoises: called: ' + aMessage + bMessage + cMessage);
return 'this the end';
},1000);
}

function test(){
// what goes here?
}

test();

Answer

Start with returning promises from your asynchronous functions instead of just calling setTimeout. Best just drop the setTimeout completely and use Promise.delay(…).then(…).

Then use then for single dependencies and Promise.join for multiple ones. Don't build long chains, store the promise for each result that you need in a variable:

function test(){
    var aPromise = a();
    var bPromise = b();
    var cPromise = bPromise.then(c);
    return Promise.join(aPromise, bPromise, cPromise, d);
}

See also the related question How do I access previous promise results in a .then() chain?.

Comments