关于ajax:如何通过加入多个异步javascript调用从对象数组中排序和获取第一个对象?

How to sort and get first obejct from array of objects get by joining multiple async javascript calls?

我有一种情况,我在 for 循环中执行多个异步 javascript Ajax 请求并异步获取对象的 json 数组中的结果(而不是在序列中),然后我必须将这些数组添加到单个数组中。

所以我的问题是如何在从循环中获取最后一个请求结果并从数组中发布第一条记录后对最终数组进行排序?
因为我是异步获取结果所以我不知道最后会处理哪个请求?
而且我不能使用同步 ajax 请求。

谢谢


最好的方法是使用 Promises。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Promise.all([
    $.get('...url1'),
    $.get('...url2')
]).then(onSuccess, onFailure);

function onSuccess(resultOfAllRequests) {
    // do something with the results of all requests
    // this won't be executed until all asynch requests are complete
    var resultOfRequest1 = resultOfAllRequests[0];
    var resultOfRequest2 = resultOfAllRequests[1];

    var singleArrayOfAllResponses = Array.prototype.concat.apply(Array.prototype, resultOfAllRequests);
    var sorted = singleArrayOfAllResponse.sort(function (a, b) {
       // this is numeric sorting. use your own sort logic
       return a - b;
    });
    var first = sorted[0]; // <-- this is what you wanted
}

function onFailure(resultOfAllRequests) {
    // one or many of the requests failed
    // handle the error(s) here
}

注意:Internet Explorer 目前不支持 Promise。这是浏览器支持的完整列表。如果您需要 IE 支持,可以使用许多为您实现 Promises 的库。最值得注意的是q。 Angular.js 也有自己的 Promise 实现,称为 $q.