javascript - Async function inside loop -
i'm newer in javascript , trying execute async function inside loop. can explain why loop continuous executing after printing "all done" here code
function asynchfunc(n, loop) { settimeout(loop, n); } function processitems(items, cb) { (function loop (index) { if (index == items.length) return cb(); console.log(items[index]); asynchfunc(items[index], loop); loop(++index); }(0)); } processitems([1000,2000,3000,4000,5000], function(ret){ console.log('all done'); });
there many problems in code:
loop call asynchloop wich call loop after n millisecond (with index == undefined).
you're test case if index == items.length. when call loop inside settimeout, pass no parameters when settimeout call loop, test case failed every time (so recursivity never ends).
if want code works need pass index in asyncfunc function , stop calling loop @ end of loop function, :
function asynchfunc(n, loop, index) { settimeout(function() { loop(++index); }, n); } function processitems(items, cb) { (function loop (index) { if (index == items.length) return cb(); console.log(items[index]); asynchfunc(items[index], loop, index); }(0)); } processitems([1000,2000,3000,4000,5000], function(ret){ console.log('all done'); });
i hope clear
Comments
Post a Comment