Run Bluebird Promises Sequentially, without return values?

和自甴很熟 提交于 2019-12-10 17:41:16

问题


This question has been asked in a variety of ways, but not quite as simply.

How would this Promise.all be rewritten so that promise1 runs completely before promise2?

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 runs promise1 & promise2 in parallel.


回答1:


You can use Promise.map with concurrency option set to 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



回答2:


Use then:

Returns a new promise chained from this promise.

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


来源:https://stackoverflow.com/questions/29546898/run-bluebird-promises-sequentially-without-return-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!