我有一个循环,可以调用API并将结果编译为数组。我如何等待所有调用完成后才能恢复执行?我看到了一系列有关如何等到打完一个电话的答案,但我不知道如何检查所有这些。如果我做一个while循环,一直等到'obj'是正确的长度,则页面只会停顿直到调用完成,这不是我想要的。请帮助?
function getData(id) {
var thisI = i;
var url = "www.whatever.com?id=" + id;
$.getJSON(url, function(data) {
obj[thisI]=data;
});
}
obj = [];
for (i=0; i < ids.length; i++) {
getData(ids[i]);
}
console.log(obj) //this works! I see all of the elements
document.getElementById("txt").innerHTML=obj[0]['field']; //TypeError: obj[0] is undefined
最佳答案
如果您使用jQuery的deferred,这很容易。有一个方法$.when
,它等待多个promise完成,然后运行回调。那就是你应该在这里使用的。
不要使用全局obj
变量,您可以只使用AJAX调用的返回值。
function getData(id) {
var thisI = i;
var url = "www.whatever.com?id=" + id;
return $.getJSON(url); // this returns a "promise"
}
因此,我们没有返回
obj
,而是返回了promise。然后在您的循环中,您收集了所有这些。var AJAX = [];
for (i=0; i < ids.length; i++) {
AJAX.push(getData(ids[i]));
}
然后我们需要在所有回调完成后挂接回调:
$.when.apply($, AJAX).done(function(){
// This callback will be called with multiple arguments,
// one for each AJAX call
// Each argument is an array with the following structure: [data, statusText, jqXHR]
// Let's map the arguments into an object, for ease of use
var obj = [];
for(var i = 0, len = arguments.length; i < len; i++){
obj.push(arguments[i][0]);
}
document.getElementById("txt").innerHTML = obj[0]['field'];
});