gpt4 book ai didi

javascript - 如何通过错误处理执行 Ajax 请求并检测整体完成情况?

转载 作者:行者123 更新时间:2023-11-29 15:26:38 24 4
gpt4 key购买 nike

再次出现某种伪同步问题......

我正在寻找在循环内完成所有 ajax 请求后运行函数的最佳实践。

坏例子:

var files = ["file1","file2","File3"];
var success = [];
var error = [];

for (var i = 0; i < files.length; i++) {
$.ajax({
type: "HEAD",
url: files[i]
}).done(function(){
console.log("file found");
success.push(files[i]);
doThisWhenAllFilesChecked();
}).fail(function () {
console.log("file not found");
error.push(files[i]);
doThisWhenAllFilesChecked();
})
}

错误示例 2:同步,只是为了说明我在寻找什么:

var files = ["file1","file2","File3"];
var success = [];
var error = [];

for (var i = 0; i < files.length; i++) {
$.ajax({
type: "HEAD",
async: false, // <-- !
url: files[i]
}).done(function(){
console.log("file found");
success.push(files[i]);
}).fail(function () {
console.log("file not found");
error.push(files[i]);
})
}
doThisWhenAllFilesChecked();

最佳答案

你可以这样做-

 var files = ["file1","file2","File3"];
var success = [];
var error = [];
var k = 0;
for (var i = 0; i < files.length; i++) {
$.ajax({
type: "HEAD",
url: files[i]
}).done(function(){
console.log("file found");
k++;
success.push(files[i]);
doThisWhenAllFilesChecked();
}).fail(function () {
k++;
console.log("file not found");
error.push(files[i]);
doThisWhenAllFilesChecked();
})
}

function doThisWhenAllFilesChecked(){
if(k==files.length){
k = 0;
//execute code here
}
}

关于javascript - 如何通过错误处理执行 Ajax 请求并检测整体完成情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38652499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com