Anders Pedersen Anders Pedersen - 1 year ago 60
AngularJS Question

How to Wait for Multiple Promises for All Data Success Callbacks

I have this API call, but I don't receive the data in my

in the same order as I send it.

for (var i = 0; i < data.length; i++) {
$'/api/bla/blabla', $.param(data[i]))
.then(successCallback, errorCallback);

var successCallback = function (response) {
receive data in random order.
assume its being send / handled so fast, thats its random
which gets done first.

Can I somehow wait for all data to be received, and then reorder it to the original ordering? or is there another solution.

Answer Source

Use $q.all to get all the data in the right order.

var promiseArray = [];
for (var i = 0; i < data.length; i++) {
    var dataPromise = $'/api/bla/blabla', $httpParamSerializer(data[i]))
        .then (function (response) {
             //return data for chaining

$q.all(promiseArray).then(function (dataArray) {
     //dataArray will be in original order
     //process results here
}).catch (function (errorResponse) {
     //log error

The promiseArray will be created in the correct order. Even though the individual XHR POST requests may not be served in the original order, the $q service will track the promises and fill the data array in the correct order (or resolve rejected on the first error).

The DEMO on JSFiddle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download