Home > Software engineering >  Async/await is blocking? if not why its result is different from promises?
Async/await is blocking? if not why its result is different from promises?

Time:11-24

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();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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" ??

CodePudding user response:

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');
    });
}

CodePudding user response:

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 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 :)

  • Related