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

158
Visualizações
Unable to track call stack of JavaScript async-await

I wrote a code and try to come up with an expected answer to understand asynchronous behavior.

I numbered the console.log lines in a way I thought it should appear, but it printed line no. 6 before line no. 5

Actual output is:

  • outside before calling 1
  • wrapper before calling 2
  • inside waiter before calling setTimeout 3
  • inside waiter after calling setTimeout 4
  • outside after calling 6
  • wrapper after calling 5
  • after 2 sec received: Hi There

I thought it would come as lines numbered in code. But line no. 5 and 6 are swapped in actual execution. can anyone explain why?

let waiter=async function (msg){
    console.log('inside waiter before calling setTimeout 3')
    setTimeout(()=>{
        console.log('after 2 sec received: ',msg)
    }, 2000);
    console.log('inside waiter after calling setTimeout 4')
}

async function wrapper(){
    console.log('wrapper before calling 2')
    await waiter('Hi There')
    console.log('wrapper after calling 5')
}

console.log('outside before calling 1')
wrapper();
console.log('outside after calling 6')
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Because wrapper is asynchronous and you are not await-ing it for it to complete, code execution continues as normal, so 6 is logged before 5.

To have the 5 logged before 6, wait for wrapper to complete with await:

console.log('outside before calling 1');
await wrapper();
console.log('outside after calling 6');
about 4 years ago · Juan Pablo Isaza Relatório

0

The function that is calling wrapper must either return or await something in order for JavaScript to relinquish control of execution back to the event loop. The handler you provided to setTimeout is initiated by the event loop and that can't start executing until the function you're currently calling either returns or awaits.

Since you did not await the call to wrapper, this function just returns a promise, which you ignore / discard by not making use of the return value of wrapper(). And execution continues past it to your 6 waypoint before the timeout handler will execute.

If the function in which all your example code resides is async then you could do:

console.log('outside before calling 1');
await wrapper();
console.log('outside after calling 6');

If await is not available at that level, then you could use .then to have something be executed when the promise completes.

let waiter=async function (msg){
    console.log('inside waiter before calling setTimeout 3')
    setTimeout(()=>{
        console.log('after 2 sec received: ',msg)
    }, 2000);
    console.log('inside waiter after calling setTimeout 4')
}

async function wrapper(){
    console.log('wrapper before calling 2')
    await waiter('Hi There')
    console.log('wrapper after calling 5')
}

console.log('outside before calling 1');
wrapper().then(() => {
   consolelog('promise returned by wrapper is now complete 6');
});
console.log('this will still happen before 5 (call it 4b)');
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