How to Wait for Multiple Promises for All Data Success Callbacks

前端 未结 3 821
迷失自我
迷失自我 2021-01-26 10:26

I have this API call, but I don\'t receive the data in my successCallback in the same order as I send it.

    for (var i = 0; i < data.length; i+         


        
3条回答
  •  忘了有多久
    2021-01-26 11:00

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

    var promiseArray = [];
    for (var i = 0; i < data.length; i++) {
        var dataPromise = $http.post('/api/bla/blabla', $httpParamSerializer(data[i]))
            .then (function (response) {
                 //return data for chaining
                 return response.data;
            })
        ;
        promiseArray.push(dataPromise);
    }
    
    $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.

提交回复
热议问题