admin管理员组

文章数量:1426959

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);
}

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);
}
Share Improve this question edited Mar 31, 2017 at 0:17 D-Marc asked Mar 30, 2017 at 23:31 D-MarcD-Marc 3,1275 gold badges23 silver badges32 bronze badges 8
  • 1 Do you mean for this code to be ajaxCallFbAPI(someArgs, function(err, data) {...}); What you show in your question does not look like a typical asynchronous API. – jfriend00 Commented Mar 30, 2017 at 23:35
  • Chaining asynchronous code to run synchronously kind of defeats the purpose of it. First thing I would try is to use Promise.all() and add your responses into your array when they're all done, this will at least allow it to only run as slow as the slowest call, not the cumulative time of all of them. – aaronw Commented Mar 30, 2017 at 23:41
  • @jfriend00 Yes you're right. I was being terse purposefully because it doesn't matter the specifics of it. Could be any async call. – D-Marc Commented Mar 30, 2017 at 23:47
  • I had the same idea as @jfriend00, his example is really good. – aaronw Commented Mar 30, 2017 at 23:48
  • 1 Well, the specifics do matter. Why don't you fix your example in your question to at least be a legal async call so people can help you more specifically (you can use the "edit" link to fix it). In general, you get better, more pertinent and more detailed answers when you show your ACTUAL code, not some make believe code example. Often the devil is in the details and we can only be thorough when we can see your actual code. Plus, we are more likely to be able to offer you an answer you didn't even know to ask about when we see the real issue and real code. – jfriend00 Commented Mar 31, 2017 at 0:03
 |  Show 3 more ments

1 Answer 1

Reset to default 8

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
});

本文标签: How to chain promises in for loop in vanilla javascriptStack Overflow