简体   繁体   English

知道何时阵列的jqXHR全部完成

[英]Know when jqXHRs of an array are all completed

I'm trying to run some code once all the jqXHR elements of an array are completed (have either succeeded or failed). 一旦数组的所有jqXHR元素都完成(成功或失败),我将尝试运行一些代码。

You can see the full code here: http://jsfiddle.net/Lkjcrdtz/4/ 您可以在此处查看完整的代码: http : //jsfiddle.net/Lkjcrdtz/4/

Basically I'm expecting the always hook from here: 基本上,我希望always从这里开始:

$.when
    .apply(undefined, reqs)
    .always(function(data) {
      console.log('ALL ALWAYS', data);
    });

to run when all the requests that were piled up there have either succeeded or failed. 当所有堆积在那里的请求成功或失败时运行。 Currently, you can observe in the console that ALL ALWAYS is logged earlier. 当前,您可以在控制台中观察到ALL ALWAYS早已记录。

A simple solution for modern browsers would be to use the newer fetch() API along with Promise.all() 对于现代浏览器,一个简单的解决方案是将较新的fetch() API与Promise.all()一起使用

 var makeReq = function(url, pos) { var finalUrl = url + pos; // intentionally make this request a failed one if (pos % 2 === 0) { finalUrl = "https://jsonplaceholder.typicode.com/423423rfvzdsv"; } return fetch(finalUrl).then(function(resp) { console.log('Request for user #', pos); // if successful request return data promise otherwise return something // that can be used to filter out in final results return resp.ok ? resp.json() : {error: true, status: resp.status, id: pos } }) }; // mock API var theUrl = "https://jsonplaceholder.typicode.com/users/"; var reqs = []; for (var i = 1; i <= 5; i++) { reqs.push(makeReq(theUrl, i)); } Promise.all(reqs).then(function(results) { console.log('---- ALL DONE ----') // filter out good requests results.forEach(function(o) { if (o.error) { console.log(`No results for user #${o.id}`); } else { console.log(`User #${o.id} name = ${o.name}`); } }) }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM