Async Await in Javascript blocking synchronous code execution

Asked

Viewed 115 times

0

If I understand correctly, a function declared with the keyword async must return a promise. In the case of the function async3() we have 1 billion iterations, which makes the return value take a little longer. What I was hoping would happen is that by invoking the function sync1() and sync2() immediately show me the log in the console and, later, the log of the function async3(). However, what I see is that the function sync1() and sync2() only show after the async3() have finished. The function would not be supposed async3() running in another thread or outside the Event loop without blocking the execution of the other functions?

Can someone clarify why this behavior?

function sync1() {
  console.log(1);
}

function sync2() {
  console.log(2);
}

async function async3() {
  let iteration = 0;
  let number = 0;
  while (iteration <= 1000000000) {
    number = iteration;
    iteration++;
  }
  return number;
}

sync1();
sync2();
async3().then((val) => console.log(val));

The function sync1() and the sync2() only show on the console after the async3() have completed all iterations. I’m confused.

1 answer

3


One mistake of yours was to assume that a function declared with async will not block the other functions just by being declared as async. Another misconception was that this function will run on another thread or outside the Event loop.

It doesn’t work that way, functions async rotate in the same thread and in the same Event loop, Moreover, they do not run in parallel, but in a competing way. This means that at no time will you have two snippets of code running simultaneously; unless you use web Workers, what I won’t discuss here.

A function async will actually lock the rest of the code while it needs to use the processor, only when functions async run an entry/exit operation involving system call, is that they can run asynchronous - while such a function waits for the answer of the system call it enters a pending state, which allows the processor to continue running the rest of the code without being blocked by the operation its function is waiting for.

In your code posted as example has nothing asynchronous, declare the function as async will not bring practical benefit as it is consuming the processor’s resources, and thus blocking the rest of the code. Then after all this clarification is the main question "why sync1() and sync2() only show on the console after async3() has completed all iterations"?

That’s because... whatever you’re using to test the code isn’t doing the flush of stdout in the moment you wait. There is no reason for the code to wait for the async3 finish to print the sync1 and sync2, in fact if you open your browser console and paste that same code, it will probably print 1 and 2 before the async3 break up.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.