How to Wait for Multiple Promises for All Data Success Callbacks

孤街浪徒 提交于 2019-12-02 10:38:16

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.

As Groben says, you could create an array of the promises for each request, and then you can use the "when" callback to execute when all are completed.

$http.get('/someUrl', config).then(successCallback, errorCallback); $http.post('/someUrl', data, config).then(successCallback, errorCallback); you can try these note the The response object has these properties:

data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.

And these too can also work depending on the API you working on...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!