按顺序运行Bluebird Promises,没有返回值?

时间:2015-04-09 19:07:11

标签: javascript node.js asynchronous promise bluebird

这个问题已经以各种方式提出,但不是那么简单。

如何重写此Promise.all以使promise1promise2之前完全运行?

var promise1 = function() { .. lots of promise stuff };
var promise2 = function() { .. lots more promise stuff };

Promise.all([promise1, promise2]).then(function() {
  log.info("ran promise1 & promise2");
});

Promise.all运行promise1& promise2并行。

2 个答案:

答案 0 :(得分:8)

您可以将Promise.map与并发选项设置为1。

var promise1 = function () {
    return new Promise(function (resolve, reject) {
        console.log("promise1 pending");
        setTimeout(function () {
            console.log("promise1 fulfilled");
            resolve();
        }, 1000)
    })
};

var promise2 = function () {
    return new Promise(function (resolve, reject) {
        console.log("promise2 pending");
        setTimeout(function () {
            console.log("promise2 fulfilled");
            resolve()
        }, 50)
    })
};

Promise.map([promise1, promise2], function (promiseFn) {
    return promiseFn(); //make sure that here You return Promise
}, {concurrency: 1}); //it will run promises sequentially 

//It logs
//promise1 pending
//promise 1 fulfilled
//promise2 pending
//promise 2 fulfilled

答案 1 :(得分:2)

使用then

  

返回从此承诺链接的新承诺。

promise1().then(function() {
  return promise2();
}).then(function() {
  log.info("ran promise1 & promise2");
});