Pedro Sturmer
Pedro Sturmer

Reputation: 594

Handling Async in Nodejs

Hey folks I'm having some trouble to solve an async issue in Node.js

let isDone = false;
setTimeOut(() => { isDone = true }, 1000)

let i = 0;
while(!isDone) {
 console.log(i++)
}

The thing is, isDone eventually becomes true, but the while keeps forever, why?

Upvotes: 2

Views: 36

Answers (1)

junvar
junvar

Reputation: 11574

Firstly, setTimeout, lowercase o.

Secondly, as James@ comment said, this is a blocking issue caused by the fact that JS is single threaded and won't resume async code (promises, timeouts, intervals) until it has a free execution cycle. To get around this, you could wrap the later part of your snippet (the while loop) inside an interval. This will give the JS engine to chance to check for ready async code at each iteration of the while

let isDone = false;
setTimeout(() => {
  isDone = true;
}, 1000);

let i = 0;
let interval = setInterval(() => {
  if (isDone)
    clearInterval(interval);
  else
    console.log(i++);
}, 0);

Upvotes: 3

Related Questions