In JavaScript, does using await inside a loop block the loop?

JavascriptAsync Await

Javascript Problem Overview


Take the following loop:

for(var i=0; i<100; ++i){
    let result = await some_slow_async_function();
    do_something_with_result();
}
  1. Does await block the loop? Or does the i continue to be incremented while awaiting?

  2. Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?

Javascript Solutions


Solution 1 - Javascript

> 1. Does await block the loop? Or does the i continue to be incremented while awaiting?

"Block" is not the right word, but yes, i does not continue to be incremented while awaiting. Instead the execution jumps back to where the async function was called, providing a promise as return value, continuing the rest of the code that follows after the function call, until the code stack has been emptied. Then when the awaiting is over, the state of the function is restored, and execution continues within that function. Whenever that function returns (completes), the corresponding promise -- that was returned earlier on -- is resolved.

> 2. Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?

The order is guaranteed. The code following the await is also guaranteed to execute only after the call stack has been emptied, i.e. at least on or after the next microtask can execute.

See how the output is in this snippet. Note especially where it says "after calling test":

async function test() {
    for (let i = 0; i < 2; i++) {
        console.log('Before await for ', i);
        let result = await Promise.resolve(i);
        console.log('After await. Value is ', result);
    }
}

test().then(_ => console.log('After test() resolved'));

console.log('After calling test');

Solution 2 - Javascript

As @realbart says, it does block the loop, which then will make the calls sequential.

If you want to trigger a ton of awaitable operations and then handle them all together, you could do something like this:

const promisesToAwait = [];
for (let i = 0; i < 100; i++) {
  promisesToAwait.push(fetchDataForId(i));
}
const responses = await Promise.all(promisesToAwait);

Solution 3 - Javascript

You can test async/await inside a "FOR LOOP" like this:

(async  () => {
        for (let i = 0; i < 100; i++) {
                await delay();
                console.log(i);
        }
})();

function delay() {
        return new Promise((resolve, reject) => {
                setTimeout(resolve, 100);
        });
}

Solution 4 - Javascript

async functions return a Promise, which is an object that will eventually "resolve" to a value, or "reject" with an error. The await keyword means to wait until this value (or error) has been finalized.

So from the perspective of the running function, it blocks waiting for the result of the slow async function. The javascript engine, on the other hand, sees that this function is blocked waiting for the result, so it will go check the event loop (ie. new mouse clicks, or connection requests, etc.) to see if there are any other things it can work on until the results are returned.

Note however, that if the slow async function is slow because it is computing lots of stuff in your javascript code, the javascript engine won't have lots of resources to do other stuff (and by doing other stuff would likely make the slow async function even slower). Where the benefit of async functions really shine is for I/O intensive operations like querying a database or transmitting a large file where the javascript engine is well and truly waiting on something else (ie. database, filesystem, etc.).

The following two bits of code are functionally equivalent:

let result = await some_slow_async_function();

and

let promise = some_slow_async_function(); // start the slow async function
// you could do other stuff here while the slow async function is running
let result = await promise; // wait for the final value from the slow async function

In the second example above the slow async function is called without the await keyword, so it will start execution of the function and return a promise. Then you can do other things (if you have other things to do). Then the await keyword is used to block until the promise actually "resolves". So from the perspective of the for loop it will run synchronous.

So:

  1. yes, the await keyword has the effect of blocking the running function until the async function either "resolves" with a value or "rejects" with an error, but it does not block the javascript engine, which can still do other things if it has other things to do while awaiting

  2. yes, the execution of the loop will be sequential

There is an awesome tutorial about all this at http://javascript.info/async.

Solution 5 - Javascript

Here is my test solution about this interesting question:

import crypto from "crypto";

function diyCrypto() {
    return new Promise((resolve, reject) => {
        crypto.pbkdf2('secret', 'salt', 2000000, 64, 'sha512', (err, res) => {
            if (err) {
                reject(err)
                return 
            }
            resolve(res.toString("base64"))
        })
    })
}

setTimeout(async () => {
    console.log("before await...")
    const a = await diyCrypto();
    console.log("after await...", a)
}, 0);

setInterval(() => {
    console.log("test....")
}, 200);

Inside the setTimeout's callback the await blocks the execution. But the setInterval is keep runnning, so the Event Loop is running as usual.

Solution 6 - Javascript

Let me clarify a bit because some answers here have some wrong information about how Promise execution works, specifically when related to the event loop.

In the case of the example, await will block the loop. do_something_with_result() will not be called until await finishes it's scheduled job.

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await#handling_asyncawait_slowdown

As for the other points, Promise "jobs" run before the next event loop cycle, as microtasks. When you call Promise.then() or the resolve() function inside new Promise((resolve) => {}), you creating a Job. Both await and async are wrapper, of sorts, for Promise, that will both create a Job. Microtasks are meant to run before the next event loop cycle. That means adding a Promise Job means more work before it can move on to the next event loop cycle.

Here's an example how you can lock up your event loop because your promises (Jobs) take too long.

let tick = 0;
let time = performance.now();
setTimeout(() => console.log('Hi from timeout'), 0);
const tock = () => console.log(tick++);
const longTask = async () => {
  console.log('begin task');
  for(let i = 0; i < 1_000_000_000; i++) {
    Math.sqrt(i);
  }
  console.log('done task');
}
requestAnimationFrame(()=> console.log('next frame after', performance.now() - time, 'ms'));
async function run() {
  await tock();  
  await tock();
  await longTask(); // Will stall your UI
  await tock();   // Will execute even though it's already dropped frames
  await tock();   // This will execute too
}
run();
// Promise.resolve().then(tock).then(tock).then(longTask).then(tock).then(tock);

In this sample, 5 total promises are created. 2 calls for tock, 1 for longTask and then 2 calls for tock. All 5 will run before the next event loop.

The execution would be:

  • Start JS execution
  • Execute normal script
  • Run 5 scheduled Promise jobs
  • End JS execution
  • Event Loop Cycle Start
  • Request Animation Frame fire
  • Timeout fire

The last line commented line is scheduling without async/await and results in the same.

Basically, you will stall the next event loop cycle unless you tell your JS execution where it can suspend. Your Promise will continue to run in the current event loop run until it finishes its call stack. When you call something external, (like fetch), then it's likely using letting the call stack end and has a callback that will resolve the pending Promise. Like this:

function waitForClick() {
  return new Promise((resolve) => {
    // Use an event as a callback;
    button.onclick = () => resolve();
    // Let the call stack finish by implicitly not returning anything, or explicitly returning `undefined` (same thing).
    // return undefined; 
  })
}

If you have a long job job that want to complete, either use a Web Worker to run it without pausing, or insert some pauses with something like setTimeout() or setImmediate().

Reshaping the longTask function, you can do something like this:

const longTask = async () => {
  console.log('begin task');
  for(let i = 0; i < 1_000_000_000; i++)
    if (i && i % (10_000_000) === 0) {
      await new Promise((r) => setTimeout(r,0));
    }
    Math.sqrt(i);
  console.log('done task');
}

Basically, instead of doing 1 billion records in one shot, you only do 10 million and then wait until the next event (setTimeout) to run the next one. The bad here is it's slower because of how much you hand back to the event loop. Instead, you can use requestIdleCallback() which is better, but still not as good as multi-threading via Web Workers.

But be aware that just slapping on await or Promise.resolve().then() around a function won't help with the event loop. Both will wait until the function returns with either a Promise or a value before letting up for the event loop. You can mostly test by checking to see if the function you're calling returns an unresolved Promise immediately.

Solution 7 - Javascript

No Event loop isn't blocked, see example below

function sayHelloAfterSomeTime (ms) {
  return new Promise((resolve, reject) => {
    if (typeof ms !== 'number') return reject('ms must be a number')
    setTimeout(() => { 
      console.log('Hello after '+ ms / 1000 + ' second(s)')
      resolve()  
    }, ms)
  })
}

async function awaitGo (ms) {
   await sayHelloAfterSomeTime(ms).catch(e => console.log(e))
   console.log('after awaiting for saying Hello, i can do another things  ...')
}

function notAwaitGo (ms) {
	sayHelloAfterSomeTime(ms).catch(e => console.log(e))
    console.log('i dont wait for saying Hello ...')
}

awaitGo(1000)
notAwaitGo(1000)
console.log('coucou i am event loop and i am not blocked ...')

Solution 8 - Javascript

>Does await block the loop? Or does the i continue to be incremented while awaiting?

No, await won't block the looping. Yes, i continues to be incremented while looping.

>Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?

Order of do_something_with_result() is guaranteed sequentially but not with regards to i. It depends on how fast the awaited function runs.

All calls to some_slow_async_function() are batched, i.e., if do_something_with_result() was a console then we will see it printed the number of times the loop runs. And then sequentially, after this, all the await calls will be executed.

To better understand you can run below code snippet:

async function someFunction(){
for (let i=0;i<5;i++){
 await callAPI();
 console.log('After', i, 'th API call');
}
console.log("All API got executed");
}

function callAPI(){
setTimeout(()=>{
console.log("I was called at: "+new Date().getTime())}, 1000);
}

someFunction();

One can clearly see how line console.log('After', i, 'th API call'); gets printed first for entire stretch of the for loop and then at the end when all code is executed we get results from callAPI().

So if lines after await were dependent on result obtained from await calls then they will not work as expected.

To conclude, await in for-loop does not ensure successful operation on result obtained from await calls which might take some time to finish.

In node, if one uses neo-async library with waterfall, one can achieve this.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsmergView Question on Stackoverflow
Solution 1 - JavascripttrincotView Answer on Stackoverflow
Solution 2 - JavascriptKris SelbekkView Answer on Stackoverflow
Solution 3 - JavascriptmzalazarView Answer on Stackoverflow
Solution 4 - JavascriptCaseyView Answer on Stackoverflow
Solution 5 - JavascriptChris BaoView Answer on Stackoverflow
Solution 6 - JavascriptShortFuseView Answer on Stackoverflow
Solution 7 - JavascriptKBHView Answer on Stackoverflow
Solution 8 - JavascriptDeeKayView Answer on Stackoverflow