[英]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。 以下是浏览器支持的完整列表。 有许多库为您实现Promises,如果您需要IE支持,可以使用它们。 最值得注意的是q 。 Angular.js也有自己的promise实现,称为$ q 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.