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

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

问题描述

我有这个 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 上的演示.

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

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