如何等待所有数据成功回调的多个承诺 [英] How to Wait for Multiple Promises for All Data Success Callbacks

查看:67
本文介绍了如何等待所有数据成功回调的多个承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个API调用,但是我的successCallback接收数据的顺序与发送顺序相同.

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++) {
      $http.post('/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.

推荐答案

使用$q.all以正确的顺序获取所有数据.

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

将按照正确的顺序创建promiseArray.即使单独的XHR POST请求可能未按原始顺序提供,但$q服务仍将跟踪承诺并以正确的顺序填充数据数组(或解决第一个错误时拒绝的问题).

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).

JSFiddle上的 DEMO .

The DEMO on JSFiddle.

这篇关于如何等待所有数据成功回调的多个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆