Skip to content Skip to sidebar Skip to footer

Running Promises In Array In Series

I have an array of links, but executing them in parallel like this makes the server hang up and time out var pages = linksArray.then(function(arr){ return arr.map(function(link

Solution 1:

the most common way of running an array of Promises in series is using array.reduce - like so

var pages = linksArray.then(function (arr) {
    var pArray = [];
    return arr.reduce(function (promise, link) {
        var ret = promise.then(function() {
            returnloader(link)
             // the next 3 lines will ensure all links are processed - any failed links will resolve with a value == false
            .catch(function(err) {
                returnfalse;
            });
        });
        pArray.push(ret);
        // next three lines log when each loader has finished
        ret.then(function() {
            console.log('finished', link);
        });
        return ret;
    }, Promise.resolve())
    .then(function() {
        returnPromise.all(pArray);
    });
})

You can then access the results like this

pages.then(function (data) {
    // data is an array of results of loaderconsole.log(data);
}).catch(function(err) { // any errors should be logged hereconsole.log(err);
});

How it works: simply, each call to loader "waits" until the previous call is resolved before being executed - the effective promise for each loader is saved in an array. Once the last loader resolves, the Promise.all returns a Promise which resolves to an array of values of each of the calls to loader

If you need to know how array.reduce works - read this

Post a Comment for "Running Promises In Array In Series"