Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

88
Views
Async/await is blocking? if not why its result is different from promises?

I do some research about async/await but I am confuse. It says that async/await is non-blocking. I look into developer.mozilla.org async function example. ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');

  const result = await resolveAfter2Seconds();
  console.log(result);

  //uncomment this code to see promise result
  //resolveAfter2Seconds().then(result=>{
  //console.log(result);
  //});

  console.log('calling end');
}

asyncCall();

async/await result is

> "calling"
> "resolved"
> "calling end"

but promise result is

> "calling"
> "calling end"
> "resolved"

so if async/await is non-blocking then why it does not console "calling end" before the "resolved" ??

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

Your Promise code isn't the same as the async variant.

async function asyncCall() {
  console.log('calling');
  
  const result = await resolveAfter2Seconds();
  console.log(result);
  
  console.log('calling end');
}

Would be the same as

function asyncCall() {
  console.log('calling');

  resolveAfter2Seconds()
    .then(result => {
      console.log(result);

      console.log('calling end');
    });
}
7 months ago · Juan Pablo Isaza Report

0

as @zhulien mentioned, The await keyword is the magic.

To understand it better execute the following code:

with await

asyncCall();
console.log("this log you will see right after 'calling' log");

without await (just remove await in asyncCall - hey you know that's fine to use async without await, but not vice versa).

asyncCall();
console.log("this log you will see right after 'calling end' log");

so in the same closure, anything after the await will be blocked, where as in code flow continues from calling function and that's what the doc meant as non-blocking :)

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs