i have loop makes calls api , compiles results array. how wait until of calls finished until resuming execution? see bunch of answers how wait until 1 call done, don't understand how check of them. if make while loop waits until 'obj' correct length, page stalls until calls done, not want. please?
function getdata(id) { var thisi = i; var url = "www.whatever.com?id=" + id; $.getjson(url, function(data) { obj[thisi]=data; }); } obj = []; (i=0; < ids.length; i++) { getdata(ids[i]); } console.log(obj) //this works! see of elements document.getelementbyid("txt").innerhtml=obj[0]['field']; //typeerror: obj[0] undefined
this easy if use jquery's deferreds. there method, $.when, waits multiple promises complete runs callback. that's should use here.
don't use global obj variable, can use returns ajax calls.
function getdata(id) { var thisi = i; var url = "www.whatever.com?id=" + id; return $.getjson(url); // returns "promise" } so, instead of populating obj, return promise. in loop, collect of them.
var ajax = []; (i=0; < ids.length; i++) { ajax.push(getdata(ids[i])); } then need hook callback when of them done:
$.when.apply($, ajax).done(function(){ // callback called multiple arguments, // 1 each ajax call // each argument array following structure: [data, statustext, jqxhr] // let's map arguments object, ease of use var obj = []; for(var = 0, len = arguments.length; < len; i++){ obj.push(arguments[i][0]); } document.getelementbyid("txt").innerhtml = obj[0]['field']; });
Comments
Post a Comment