17

I have three snippets that loop three times while awaiting 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 awaits 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--;
  })();
}

Can someone explain why they exhibit these different behaviors? Thanks.

Ahmed Karaman
  • 523
  • 3
  • 12

4 Answers4

16

Concerning your second snippet:

Caling an async function without awaiting it's result is called fire and forget. You tell JavaScript that it should start some asynchronous processing, but you do not care when and how it finishes. That's what happens. It loops, fires some asynchronous tasks, when the loop is done they somewhen finish, and will log 0 as the loop already reached its end. If you'd do:

await (async () => {
  await Promise.resolve();
  console.log(i);
})();

it will loop in order.

Concerning your third snippet:

You never decrement i in the loop, therefore the loop runs forever. It would decrement i if the asynchronous tasks where executed somewhen, but that does not happen as the while loop runs crazy and blocks & crashes the browser.

 let i = 3;
 while(i > 0) {
   doStuff();
 }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
9

Focusing primarily on the last example:

let i = 3;
while (i) {
  (async () => {
    await Promise.resolve();
    console.log(i);
    i--;
  })();
}

It may help if we rewrite the code without async/await to reveal what it is really doing. Under the hood, the code execution of the async function is deferred for later:

let callbacks = [];

let i = 0;
while (i > 0) {
  callbacks.push(() => {
    console.log(i);
    i--;
  });
}

callbacks.forEach(cb => {
  cb();
});

As you can see, none of the callbacks are executed until after the loop is completed. Since the loop never halts, eventually the vm will run out of space to store callbacks.

Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
2

In your particular example it decrements the i and then runs the async code like:

let i = 3;

while (i) {
  i--; // <---------------------
  (async () => {            // |
    await Promise.resolve();// |
    console.log(i);         // |
  })();                     // |
 // >---------------------------
}

Regarding your third snippet, it will never decrease the i value and so loop runs forever and thus crashes application:

let i = 3;
while (i) {
  (async () => {
    await Promise.resolve(); // await and resolve >-----------
    // the following code doesn't run after it resolves   // |
    console.log(i);                                       // |
    i--;                                                  // |
  })();                                                   // |
  // out from the (async() => {})() <-------------------------
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Not really, If you would remove the `await Promise.resolve` it would log correctly. – Jonas Wilms Mar 24 '19 at 12:16
  • @Bhojendra Rauniyar Can you please check this third snippet? – Ahmed Karaman Mar 24 '19 at 12:37
  • @JonasWilms Does what you say mean that if we have an `async` function without an `await` in its body that it will be blocking and run synchronously like any other function? – Ahmed Karaman Mar 24 '19 at 13:35
  • @AhmedKaraman yes, it will, except that if you return something from it, that will be deferred too – Jonas Wilms Mar 24 '19 at 13:58
  • @AhmedKaraman I was heading to home from my office just after posting my answer. I have now updated with your query. – Bhojendra Rauniyar Mar 24 '19 at 14:11
  • 2
    `the asynchronous code runs in background` this is incorrect. The async code is deferred, and since event loop is busy with infinite while loop the async code never runs. if it was in background, the output numbers would be random but the `i` would be equal to zero eventually. – meze Mar 24 '19 at 14:28
  • @meze Isn't it similar? async runs in background and await halts until it is resolved... Maybe I'm not understanding the term deferred and background process? – Bhojendra Rauniyar Mar 24 '19 at 14:31
  • @meze It would be my pleasure to understand if you could edit that particular sentence in my answer that fits. Thanks in advance. – Bhojendra Rauniyar Mar 24 '19 at 14:35
  • 1
    @BhojendraRauniyar JavaScript is single-threaded, so there is no “background”. Only one chunk of code can run at one time. I’m fuzzing over some of the details here, but there is a single event loop that dequeues a pending callback and runs it to completion. In order to prevent blocking (such as waiting for a timer or a network request), code is broken up into smaller callbacks in order to give competing events their chance to run in the single thread. `await` is just syntactic sugar for “schedule a callback to run after the thing we’re waiting on is available”. – Joel Cornett Mar 24 '19 at 15:14
2

Because in the first case console.log and decrement work in sync with each other because they are both inside the same asnychronous function. In the second case console.log works asynchronously and decrement works synchronously. Therefore, the decrement will be executed first, the asynchronous function will wait for the synchronous function to finish, then it will be executed with i == 0

In the third case, the loop body executes synchronously, and runs the asynchronous function at each iteration. Therefore, the decrement can not work until the end of the loop, so the condition in the cycle is always true. And so until the stack or memory is full

Nikita Umnov
  • 146
  • 1
  • 1
  • 10