5

I want to sequentially execute some asynchronous functions based on an array.

I thought this would do it :

var Promise = require("bluebird");
Promise.cast([1,2,3]).reduce(function(_,i){
    console.log("Launching  " + i);
    return Promise.delay(Math.floor(Math.random()*1000)).then(function(){
        console.log("Executing  " + i);
    });
},0);

but I get

Launching  1
Launching  2
Launching  3
Executing  2
Executing  1
Executing  3

instead of the desired result which would be

Launching  1
Executing  1
Launching  2
Executing  2
Launching  3
Executing  3

How can I ensure wholly sequential execution here ?

Note that I know how to do that without promises, I'm only interested in full promises solutions.

1 Answer 1

2

You are using an old version of Bluebird. The behavior of .reduce was changed in v1 to work this way:

Like .map and .filter, .reduce now allows returning promises and thenables from the iteration function.

( from the changelog )

Please update to the most recent version. This will cause the code to run correctly.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, upgrading Bluebird to 1.0.8 fixed the problem.
If anyone is reading this and is "stuck" on a < v1 version of Bluebird and can't update - let me know and I'll add a < v1 answer - otherwise, I'd rather not so more people upgrade to modern Bluebird.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.