假设我有这个功能:
function testAjax(url) {
return $.ajax({
url: url,
type: 'GET'
});
}
现在我有很多节点(我正在使用D3),我希望循环遍历。每个文件可能有也可能没有关联的一些文件。为了查明是否存在,我获取所选节点上的 url,检查返回的数据,如果它有一个/多个文件,我将其添加到文件数组中。然后,我希望仅在遍历每个节点并检查它以查看它是否有文件后才记录文件数组。
其余代码与此类似:
var allFiles = [];
nodes.each(function(d) {
testAjax(d.url)
.success(function(data) {
if (data.files) {
if (data.files.length > 0) {
for (var i = 0; i < data.files.length; i++) {
allFiles.push(data.files[i])
}
}
}
})
})
//Here is where I want to log/use (call a function passing the files array as an argument) the array of files after its been completed.
最佳答案
创建 Promise 数组并使用 $.when()
解析完整数组后进行解析
var allFiles = [];
var promises = [];
nodes.each(function(d) {
// reference to promise
var req= testAjax(d.url)
.success(function(data) {
if (data.files) {
if (data.files.length > 0) {
for (var i = 0; i < data.files.length; i++) {
allFiles.push(data.files[i])
}
}
}
})
});
// push to array
promises.push(req);
});
$.when.apply(null, promises).then(function(){
// all promises have been resolved here
}).fail(function(){
alert('Opps ... something went wrong with one of the requests')
})
关于javascript - 所有 ajax 调用完成后如何运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38459926/