问题
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