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); 

jsfiddle

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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -