javascript - Make sure all async calls have been completed in jQuery -
i have webapp doing bunch of async api calls using jquery:s $.get , $.post methods. need make sure these have finished (http status code 200) before activate button (display: none/block).
is there way make sure there no outstanding async calls waiting out-of-the-box in jquery? or need keep track of myself?
i'm using jquery v1.8.3.
you can create "master deferred", resolve when of other deferreds (the ajax requests) have completed successfully;
jquery.when(jquery.get('/foo'), jquery.post('/bar'), jquery.get('/baz')).done(function () { $('button').show(); });
the syntax pass each deferred
parameter jquery.when()
, returns deferred
resolves when 1 fails, or when of them complete.
if don't know beforehand how many ajax requests have, have them in array, or don't want use above, can use function.apply
so;
var ajaxrequests = [jquery.get('/foo'), jquery.post('/bar'), jquery.get('/baz')]; jquery.when.apply(jquery, ajaxrequests).done(function () { $('button').show(); });
for more info, see http://api.jquery.com/jquery.when, or http://www.mattlunn.me.uk/blog/2014/01/tracking-joining-parallel-ajax-requests-with-jquery/ (my blog)
Comments
Post a Comment