Javascript – Promise.each and Promise.map

Date: 2016-08-31

Implementation:

Promise.map = function(arr, fn) {
    return Promise.all(arr.map(function(i) { return fn(i) }));
};

Promise.each = function(arr, fn) {
    return arr.reduce(function(p, i) {
        return p.then(function(r) {
            return fn(i);
        });
    }, Promise.resolve());
};

Example usage:

var subtaskAsync = function(id) {
    return new Promise(function(resolve, reject) {
        console.log(new Date().getTime(), 'subtaskAsync', id);
        setTimeout(function() {
            resolve(id);
        }, 200);
    });
};

var taskAsync = function(id) {
    console.log(new Date().getTime(), 'taskAsync', id);
    return Promise.map([1, 2], subtaskAsync); // parallel
};

Promise.each([1, 2, 3], taskAsync); //sequential
4600cookie-checkJavascript – Promise.each and Promise.map