Skip to main content

Runs an array of promises in series.

/**
 * Runs an array of promises in series.
 *
 * Use Array.prototype.reduce() to create a promise chain, where each
 * promise returns the next promise when resolved.
 *
 * @param {array} ps Promises
 * @returns {*}
 * @example
 * var delay = function(d) {
 *    return new Promise(function(r) {
 *        return setTimeout(r, d);
 *    });
 * };
 *
 * // Executes each promise sequentially, taking 3 seconds to complete
 * runPromisesInSeries([
 *     function() {
 *            return delay(1000);
 *        },
 *     function() {
 *            return delay(2000);
 *        }
 *     ]);
 * @link https://www.30secondsofcode.org/js/s/run-promises-in-series/
 */
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());

// ES5
var runPromisesInSeries = function(ps) {
    return ps.reduce(function(p, next) {
        return p.then(next);
    }, Promise.resolve());
};

//
// Example usage:

var delay = function(d) {
    return new Promise(function(r) {
        return setTimeout(r, d);
    });
};

runPromisesInSeries([
    function() {
        return delay(1000);
    },
    function() {
        return delay(2000);
    }
]); // Executes each promise sequentially, taking a total of 3 seconds to complete