等待,而文件已准备就绪
问题描述:
一些文件被创建在后端(最多1分钟)。我写了一个函数来检查文件是否准备就绪等待,而文件已准备就绪
function check_for_file() {
$.ajax({
url: '/check/', // check if file exists
success: function(data) {
location.replace('/hello/'); // redirect to download
return true;
},
failure: function(data) {
alert('Got an error');
}
});
return false
}
a = check_for_file();
}
// a= false
// while (a == false) {
// a = check_for_file();
// }
console.log(a);
这工作正常。但是我需要做一个循环来检查文件没有准备好的时候。我该怎么办?
!!!!!!!! 看的第一个评论的答案
答
a = check_for_file();
将立即返回。
您不能运行异步并返回结果。
failure
是不是顺便说一个事件 - 它被称为失败或错误
呼叫的成功afgain功能,错误/失败或完成的测试文件后使用setTimeout的中签未准备好/完成或取决于你如何传递失败 “文件暂时还没有发现”
function check_for_file() {
$.ajax({
url: '/check/', // check if file exists
success: function(data) {
if (data.fileExists) { // result from server
location.replace('/hello/'); // redirect to download
}
else {
setTimeout(check_for_file,2000); // try again
}
},
error: function(data) {
alert('Got an error');
}
});
}
'A = check_for_file();'将立即返回。您不能运行异步并返回结果。在失败时调用函数afgain或者在测试文件没有准备好时使用setTimeout在成功/完成或失败后调用函数,具体取决于您如何显示失败 - 失败不是顺便说明的事件 - 它被称为失败或错误 – mplungjan