jquery - How do I trigger something only when batch of getJSON instructions completes? -
here's of code:
for (var = 0; < recordlist.length; i++) { var recordid = recordlist[i]; populatedatarow(i, recordid, columns) }; console.log("done");
here populatedatarow
function uses $.getjson
problem (in google chrome @ least), console.log
statement triggered long before populatedatarow
cycles completed
yes, console.log
happens first because getjson
asynchronous. code starts it, finishes later, after subsequent code runs.
to handle that, you'll need use "completion" callback on getjson
. code above remember how many calls it's started, , wait many completions before continuing.
you can have populatedatarow
function return return value of getjson
, save objects, , use jquery.when
notification when they've finished.
here's example: live copy | live source
var deferreds = [], index; (index = 0; index < 4; ++index) { deferreds.push($.getjson("http://jsbin.com/agidot/1", function() { display("one finished"); })); } $.when.apply($, deferreds).then(function() { display("all finished") }); function display(msg) { $("<p>").html(string(msg)).appendto(document.body); }
note see "all finished" when 4 calls have finished.
the call $.when
bit of hassle. reason, can't pass array of deferred
objects it. used function#apply
call , pass each entry of array discrete argument.
i surprised $.when
doesn't accept array , handle usefully, see other answers here saying use apply
: here , here.
if going use arrays lot, think i'd have in standard toolkit of jquery extensions:
(function($) { $.whenall = function(deferreds) { return $.when.apply($, deferreds); }; })(jquery);
...and end of code example above be:
$.whenall(deferreds).then(function() { display("all finished") });
Comments
Post a Comment