如何为所有数据成功回调等待多个 Promise

编程入门 行业动态 更新时间:2024-10-27 09:41:38
本文介绍了如何为所有数据成功回调等待多个 Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有这个 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 10:06:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1000411.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   回调   何为   数据   Promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!