node.js - How to use promises to simulate a synchronous for loop -
i cannot promises work (the way think should). following code executes immediately. ie. not wait 4 seconds before logging each number console.
function do_nothing(a) { return new promise(function(accept, reject){ console.log(a) settimeout(accept(parseint(a)+1), 4000); }); } function do_til_finish(i) { if (parseint(i) < 5) { do_nothing(i) .then(j => do_til_finish(j)) .catch(j =>{}) } else { console.log('all done'); } } do_til_finish(0);
what missing?
btw. not want run loop asynchronously statements use memory , freeze server.
this not webserver dont need worry frustrating users.
thanks in advance
you not using function inside settimeout
.
try this:
function do_nothing(a) { return new promise(function(accept, reject){ console.log(a) settimeout(function(){accept(parseint(a)+1)}, 4000); }); } function do_til_finish(i) { if (parseint(i) < 5) { do_nothing(i) .then(j => do_til_finish(j)) .catch(j =>{}) } else { console.log('all done'); } } console.log("\n"); do_til_finish(0);
Comments
Post a Comment