等待多的getJSON调用来完成 [英] Wait for multiple getJSON calls to finish
问题描述
我有一个循环,将调用的API,并编译结果到一个数组。我怎么等到所有的呼叫都完成,直到恢复执行?我看到一堆答案如何要等到一个呼叫做的,但我不知道如何检查他们。如果我做一个while循环等待,直到OBJ是正确的长度,页面只是延缓,直到呼叫完成,这是不是我想要的。帮助吗?
函数的getData(ID){
VAR thisI =我;
VAR URL =www.whatever.com?id=+ ID;
$ .getJSON(URL,功能(数据){
OBJ [thisI] =数据;
});
}
物镜= [];
对于(i = 0; I< ids.length;我++){
的getData(IDS [I]);
}
执行console.log(OBJ)//这个作品!我看到所有的元素
。的document.getElementById(TXT)的innerHTML = OBJ [0] ['场']; //类型错误:OBJ [0]是未定义
如果你使用jQuery的deferreds这很容易。有一种方法, $。当
,即等待多的承诺,完成然后运行一个回调。这是你应该使用这里的东西。
不要使用全局 OBJ
变量,你可以使用来自AJAX的回报调用。
函数的getData(ID){
VAR thisI =我;
VAR URL =www.whatever.com?id=+ ID;
返回$ .getJSON(URL); //这会返回一个承诺
}
因此,而不是填充 OBJ
,我们只是回到了承诺。然后,在你的循环,你收集他们所有。
VAR AJAX = [];
对于(i = 0; I< ids.length;我++){
AJAX.push(的getData(IDS [I]));
}
然后,我们需要挂钩回调时,所有的人都做了:
$。when.apply($,AJAX).done(函数(){
//这个回调将调用多个参数,
//为每个AJAX调用
//每个参数是一个数组具有以下结构:数据,状态文本,jqXHR]
//让我们映射的参数为对象,以方便使用
VAR OBJ = [];
对于(VAR I = 0,len个=与arguments.length; I< LEN;我++){
obj.push(参数[I] [0]);
}
。的document.getElementById(TXT)的innerHTML = OBJ [0] ['场'];
});
I have a loop that makes calls to an API and compiles the results into an array. How do I wait until all of the calls are finished until resuming execution? I see a bunch of answers for how to wait until one call is done, but I don't understand how to check for all of them. If I make a while loop that waits until 'obj' is the correct length, the page just stalls until the calls are done, which is not what I want. Help please?
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
This is easy if you use jQuery's deferreds. There is a method, $.when
, that waits for multiple promises to complete then runs a callback. That's what you should use here.
Don't use a global obj
variable, you can just use the returns from the AJAX calls.
function getData(id) {
var thisI = i;
var url = "www.whatever.com?id=" + id;
return $.getJSON(url); // this returns a "promise"
}
So, instead of populating obj
, we just return the promise. Then in your loop, you collect all of them.
var AJAX = [];
for (i=0; i < ids.length; i++) {
AJAX.push(getData(ids[i]));
}
Then we need to hook up the callback when all of them are done:
$.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'];
});
这篇关于等待多的getJSON调用来完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!