javascript - Can I declare a non-global variable to store asynchronous values? -
i have multiple javascript files. have js function runs upon load contains multiple ajax calls. each ajax phone call performs callback (as increments synchronous counter):: myarray.push('somevalue');
so can verify when ajax calls (for js file) have finished.
is there way can away not declaring myarray global variable, while allowing asynchronous callbacks force array?
if want execute code after set number of ajax requests have completed, utilize $.when
.
if using myarray
solely know when requests finished, can remove it. if using store result of each request, can maintain in same scope requests , access in done
handler. seek this:
var myarray = []; var ajax1 = $.ajax({ url: '/foo/', success: function(data) { myarray.push(data); }); }); var ajax2 = $.ajax({ url: '/bar/', success: function(data) { myarray.push(data); }); }); $.when(ajax1, ajax2).done(function() { // both requests finish // myarray contain info of both requests @ point... (var = 0; < myarray.length; i++) { console.log(myarray[i]); } });
javascript jquery ajax scope
No comments:
Post a Comment