Skip to content Skip to sidebar Skip to footer

Run Bluebird Promises Sequentially, Without Return Values?

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 =

Solution 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

Solution 2:

Use then:

Returns a new promise chained from this promise.

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

Post a Comment for "Run Bluebird Promises Sequentially, Without Return Values?"