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