Posts

Showing posts from May 2, 2019

Why does Async/Await work properly when the loop is inside the async function and not the other way around?

Image
12 1 I have three snippets that loop three times while await ing on a promise . In the first snippet, it works as I expect and the value of i is decremented with each await . let i = 3; (async () => { while (i) { await Promise.resolve(); console.log(i); i--; } })(); Output: 3 2 1 In the second one, the value of i is continuously decremented until it reaches zero and then all the await s are executed. let i = 3; while (i) { (async () => { await Promise.resolve(); console.log(i); })(); i--; } Output: 0 0 0 Lastly, this one causes an Allocation failed - JavaScript heap out of memory error and doesn't print any values. let i = 3; while (i) { (async () => { await Promise.resolve(); console.log(i); i--; })();