There are two async functions. One would set a variable, and the other one will wait for the vairable to change, like the code shown below. Even though the common practice is to use events or Promises, it was not viable in my situation.
function delay(ms: number): Promise<void> {
return new Promise(resolve => {
setTimeout(() => { resolve(); }, ms);
});
}
function async fn1() {
let done = false;
(async () => {
await delay(100); // simulate some work
done = true;
})();
await (async () => {
while (!done) { }
// do other things
})();
}
function async fn2() {
let done = false;
(async () => {
await delay(100); // simulate some work
done = true;
})();
await (async () => {
while (!done) {
await delay(200); // introduce some extra delay
}
// do other things
})();
}
I wonder why the fn1
would stuck in the while
loop but fn2
will work.
Since the only difference between them is that the latter one
introduced some extra waiting. Is this related to some underlying
thread scheduling mechanisms of NodeJS/V8 interpreter?
I am using Node 12.18.3 and TypeScript 4.0.3.
EDIT: fixing the definition of fn2
.