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

243
Visualizações
If I use async/await, it doesn't run in order

I have a question about the async/await execution.

example codes

async firstMethod(){
  new Promise((resolve, reject)) => {
     setTimeout(() => {
        resolve("test1");
     }, 3000);     
  });
}

async secondMethod() {
  new Promise((resolve, reject)) => {
     setTimeout(() => {
        resolve("test2");
     }, 1000);     
  });
}

await firstMethod();
await secondMethod();

So, When the two methods are executed, the following results are obtained.

test2
test1

However, if a return is attached, the result value is as follows.

async firstMethod(){
  return new Promise((resolve, reject)) => {
     setTimeout(() => {
        resolve("test1");
     }, 3000);     
  });
}

async secondMethod() {
  return new Promise((resolve, reject)) => {
     setTimeout(() => {
        resolve("test2");
     }, 1000);     
  });
}

await firstMethod();
await secondMethod();
test1
test2

Why is that? I'd appreciate it if you could explain it.

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

0

In the first case you just await the outer promises (that are the firstMethod and secondMethod functions) and the inner promises created by new Promise do not get awaited, and simply run to completion in the background.

In the second case, because of promise unwrapping you await the returned inner promises together with the outer function promises.

about 4 years ago · Juan Pablo Isaza Relatório

0

The reason why in the first example those 2 functions do not run in order is because you are not waiting for anything. If you try to remove the async from the function definition in the first example you will get the same result because the function does not need the async because it does not require an await. What you could do to have the same result has the second example is by adding a await before the new Promise.

Note: You also do not need the async in the second example because you are not waiting for anything, you are just returning a Promise in which you wait outside the scope.

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