Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
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" ??

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

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');
    });
}
about 4 years ago · Juan Pablo Isaza Relatório

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda