简体   繁体   中英

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) {
              return loader(link);
              });
          }).then(function(data){
            console.log(data);
            return data;
          });

How can I load the pages that are associated with the array of links, in series? loader is a promise that gets the html

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() {
            return loader(link)
             // the next 3 lines will ensure all links are processed - any failed links will resolve with a value == false
            .catch(function(err) {
                return false;
            });
        });
        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() {
        return Promise.all(pArray);
    });
})

You can then access the results like this

pages.then(function (data) {
    // data is an array of results of loader
    console.log(data);
}).catch(function(err) { // any errors should be logged here
    console.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM