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

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

我遇到这样一种情况,我在一个 for 循环中执行多个异步 javascript Ajax 请求并在 json 对象数组中异步获取结果(不在序列中)然后我必须取消那些数组以制作一个数组。

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

谢谢

最好的方法是使用 Promises

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。 Here is the complete list of browser support. There are many libraries that implement Promises for you that you can use if you need IE support. Most notably q. Angular.js also has its own promise implementation called $q.