Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda