1

how can I run the tasks sequentially one by one if use bluebird? I have a tasks lists, every task is depends previous task's result, but the tasks might be a async job. Following code is not work, should I use promise.all or other function? the "then" chain make me confused, the f2 run directly rather than wait f1 complete (and i also dont know how to "resolve" f1)

var Promise = require("bluebird");

function f1(p1){
    console.log("init value or f2 return:"+p1);

    var p = Promise.resolve();

    setTimeout(function(){
        var r = "aysnc result";

        // how can i notify next step when a async operation done?
        // there is no p.resolve function
    },1000)

    return p;
}

function f2(p1){
    console.log("f1 said:"+p1);
    return "f2 result";
}

var p = Promise.resolve("init value")
    .then(f1)
    .then(f2)
    .then(f1)
    .done(function(result){
        console.log("f3 result:"+result);
    })
johugz
  • 2,023
  • 2
  • 13
  • 9

1 Answers1

2

You're creating async functions incorrectly, your chaining with .then should work but your setTimeout never waits for r to change.

To create promises from arbitrary callbacks use the promise constructors:

function f1(p1){
    console.log("init value or f2 return:"+p1);

    return new Promise(function(resolve){
        setTimeout(function(){
            resolve("aysnc result");
        },1000)
    });
}

Here is the generic question on how to do this.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504