How to chain promises in for loop in vanilla javas

2019-03-02 06:46发布

问题:

If I am doing an async call like the following, how can chain them with promises, so i can do stuff in order? In this example, what ends up happening is that arr will push the items out of order. I'd prefer an answer with promises, but anything will do as long as it works

var fbArrOfAlbumNames = ['Profile Pictures', 'Cover Photos', 'Mobile Uploads'];
var arr = [];
for(var x = 0; x < fbArrOfAlbumNames.length; x++) {
  (function(cntr) {
    FB.api('/' + fbArrOfAlbumNames[cntr] + '/photos/', {fields: 'picture,album'}, function(response) {
      arr.push(response);
    }
  })(x);
}

回答1:

Assuming your ajax calls can actually be run in parallel and you just want the results in order, then you can promisify the ajax function and use Promise.all() to get all the results in order:

// promisify the ajax call
function fbAPIPromise(path, args) {
    return new Promise(function(resolve, reject) {
        FB.api(path, args, function(results) {
            if (!result) return resolve(null);
            if (result.error) return reject(result.error);
            resolve(result);
        });
    });
}

var promises = [];
for (var x = 0; x < 10; x++) {
     promises.push(fbAPIPromise('/' + fbArrOfAlbumNames[x] + '/photos/', {fields: 'picture,album'});
}
Promise.all(promises).then(function(results) {
     // results is an array of results in original order
}).catch(function(err) {
     // an error occurred
});