在函数内等待forEach中的Ajax调用
我被一个必须处理数组的函数卡住,并且作为它的一部分,它必须遍历它并使用值执行ajax调用以确定它是否有效。如果发现错误,它会在处理完所有数据后返回一串错误消息。在函数返回之前,如何确保ajax调用全部完成,并记住它们只会在某些循环中触发?在函数内等待forEach中的Ajax调用
我已经尝试了各种延期/承诺相关的事情,但不能得到它:( 我不认为这是因为forEach,“我如何获得返回异步数据”,直截了当,或者即使原理是相同的,我正在努力与implimentation
修剪的代码下面 - 注意/ /其他的东西 - 都在forEach的情况下,如果有所作为的观众调用handleFileSelect()
,然后呼吁basicValidation()
;
function basicValidation(data) {
// Store errors to be returned.
var failed = '';
// Loop over each row and validate.
data.forEach(function(row, index) {
// Do other stuff.
if (a) {
// Do stuff.
} else if (b) {
// Do ajax bit that only happen sometimes.
$.ajax({
url: 'https://api.postcodes.io/postcodes/' + row[5],
success: function (data) {
if (200 !== data.status) {
failed += 'Row ' + index + ':: invalid Address - lookup failed.\n';
}
// Do other checks.
},
error: function (request, status, error) {
console.log( 'Postcode lookup request failed:: ' + request.responseText + '\n' + status + '\n' + error);
}
});
}
// Do other stuff.
}
return failed;
}
function handleFileSelect(results) {
// Do the basic front-end validation.
var validation = basicValidation(results.data);
if (validation.length) {
alert('Failed.\n\n' + validation + '\nPlease correct your data, refresh the page, and try again.');
return false;
}
}
你有没有尝试设置async: false
在你的AJAX?
根据docs:
异步(默认值:true)类型:Boolean默认情况下,所有的请求被发送异步 (即这是默认设置为true)。如果您需要 同步请求,请将此选项设置为false。
这将等待响应,然后再继续。
// Do ajax bit.
$.ajax({
url: 'https://api.postcodes.io/postcodes/' + row[5],
async: false,
success: function (data) {
if (200 !== data.status) {
failed += 'Row ' + index + ':: invalid Address - lookup failed.\n';
}
// Do other checks.
},
error: function (request, status, error) {
console.log( 'Postcode lookup request failed:: ' + request.responseText + '\n' + status + '\n' + error);
}
});
主线程中的同步请求已被弃用 –
使用'async:false'是非常糟糕的做法。 – PredatorIWD
谢谢你的回答@ jeramiah-harland - 但是这给了我可怕的弃用警告! – phil
直视'$ .when' –
你的大问题是,无论你已经展示的功能要返回同步结果('failed'返回FALSE) - 一旦你这是不可能发生引入异步代码 - 所以,如何调用handleFileSelect也将需要更改 –
谢谢@JaromandaX - 但我需要更多的手持方式。我可以使用$ .Deferred()和$ .when做一个基本的异步函数,但是我无法在这个特定的上下文中使用它。 – phil