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

206
Visualizações
What's the difference between await an async function and directly calling an async function

I recently read a book about async and await patterns, there's chapter about deferred await or early init. The book says:

This allows a structure that starts async processing early but only stops for it when the result is needed.

const wait = (ms) => new Promise(res => setTimeout(res, ms));

const fn = async () => {
  console.log("starting");
  await wait(100); // I suppose await should pause the execution
  console.log("end");
}

(async () => {
  const fnPromise = fn();
  console.log("after"); // However after is printed brfore end
  await fnPromise;
})();

And if I change the code a bit

(async () => {
  await fn(); // looks like the inner await only takes effect when I await an async function
  console.log("after"); // after is printed after end
})();

I mean what's the difference between await an async function and directly calling it. Is there any best pratice about when to await or when not to await an async function. Does await truly block the execution, especially combined with timers. Thanks to @asynts's snippet, I'll post it here

let samples = 100 * 1000 * 1000;
let chunk = 100000;

async function run() {
    let sum = 0.0;
    for(let i=0; i<samples; i++) {
        sum += Math.random();

        if (i % chunk === 0) {
            console.log("finished chunk")
            // wait for the next tick
            await new Promise(res => setTimeout(res, 0));
            // If await truly blocks the execution, rest of the code are all waiting? 
            // If await doesn't block the execution, what's the point to await here
        }
    }

    let mean = sum / samples;
    console.log("finished computation", mean);
}

setTimeout(run, 0);

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

0

What's the difference between await an async function and directly calling it.

Well, you already observed the difference clearly in your first two snippets.

Is there any best practice about when to await or when not to await an async function?

Yes: always do it immediately. Do not let promises sit around un-awaited (like your fnPromise variable).

Not doing so is not necessarily wrong, but it increases the likelihood of mistakes:

  • it makes the order of execution less obvious and the code harder to understand
  • it can cause rejections to be missed (not handled) while doing something else (e.g. waiting for something else, or even conditionally breaking from a loop etc.) which may cause your program to crash. See Waiting for more than one concurrent await operation or Any difference between await Promise.all() and multiple await?
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