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

171
Visualizações
Understanding of async/await and promises

I am working in node.js v18.2.0 and here is my code:

async function res_asyncf(){
  await setTimeout(r => {}, 1000);
}
const res_promise = new Promise(async r => {
  await setTimeout(r, 1000);
});

async function not_res_asyncf(){
  while(true){ }
}
const not_res_promise = new Promise(async r => { });

(async () => {

  console.log("Async wrapper entered");
  await <async_thing_here>;
  console.log("Promise resolved");

})();

Instead of <async_thing_here> I was writing res_asyncf(), res_promise, not_res_asyncf() and finally not_res_promise.

The first one did not wait, which I do not understand.

The second behaved as expected: it hung for a second and then Promise resolved was printed.

The third one also behaved as expected: it hung forever.

But the last one just did nothing and exited and even did not print Promise resolved. Expected: it hangs just as the third one.

Why does all this happen?

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

0

There still confusion about async / await. They put await infront of everything and expect it to be awaited somehow magically, but thats not how it works.

await makes ONLY sense to use it on Promises. setTimeout does not return an promise, so its nonsense to use it on it.

If you want to use async / await then just ask 2 Questions:

  1. Does this function, method etc. returns an promises?

    1.1 If yes, you could use async / await

    1.2 If no, dont use it. It probably makes no sense.

In your case you have setTimeout:

  1. Does it return an Promise?

Well, you might say, i dont know.

But you can google it: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout

The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout()

Now we get to

1.2 If no, dont use it. It probably makes no sense.

Let me rewrite it:

const res_promise = new Promise(r => {
   setTimeout(r, 1000);
});

function not_res_asyncf(){
  while(true){ }
}
const not_res_promise = new Promise(r => {  });

(async () => {

  console.log("Async wrapper entered");
  await not_res_promise;
  console.log("Promise resolved");

})();

The first function is nonsense. You can technically use await on setTimeout it wont throw you an error, but in praxis it just does nothing.

The second function does need async / await at all.

The third also does not need async / await and its blocking the main thread.

The last one does also need async. It does nothing because it never gets resolved or rejected. Its in an pending state.

Differenz between your third and last function is:

Your third function blocks your entire main thread and makes your application unresponseable.

Your last function returns an promise in an pending state wich does not block your main thread and your application is still responseable.

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