javascript - Iterating over synchronous ajax calls with promises -
i have jquery code looks bit this:
for ( = 0; < limitvar; i++ ) { doajaxstuff(i); } function doajaxstuff( ) { here make synchronous ajax call, sending i. }
the ajax call needs synchronous - 1 isn't fired until last 1 done.
as synchronous js deprecated, want move code use promises. how achieve this? i've been unable find example close enough fits situation.
you don't synchronous ajax in browser (well technically, can in circumstances, it's bad idea because locks browser during ajax call).
instead, redesign loop carries out next ajax call when previous 1 done means have loop manually, can't use for
loop. since code pseudo-code (you don't show real ajax operation), i'll use jquery ajax example, can substitute ajax function have long either returns promise or uses callback signal when done.
the general idea create function ajax call , use completion callback increment index , run next iteration of loop.
function runloop(data) { var = 0; function next() { if (i < data.length) { return $.ajax(data[i]).then(function(data) { ++i; return next(); }); else { // done loop } } return next(); } // call runloop(somearray).then(function() { // done here });
if don't have array of data, want loop index:
function runloop(limitvar) { var = 0; function next() { if (i < limitvar) { return $.ajax(something_with_i_in_it).then(function(data) { ++i; return next(); }); else { // done loop } } return next(); } // call runloop(thelimit).then(function() { // done here });
if limitvar not large , there no other logic involved in deciding whether continue loop, can use little bit simpler pattern if have ajax function returns promise:
function runloop(limitvar) { var p = promise.resolve(); (var = 0; < limitvar; i++) { p = p.then(function(prevresult) { return someajax(i); }); } return p; } // call runloop(thelimit).then(function() { // done here });
if aren't using ajax functions return promise, it's few lines of code wrap function 1 , can more use these design patterns.
Comments
Post a Comment