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

84
Vistas
multiple awaits are running in parallel

I'm trying to learn async/await and promises and unable to make run multiple async functions in serial.

function firstFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('first'), 2000)
    resolve()
  })
}

function secondFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('second'), 1000)
    resolve()
  })
}

async function main() {
  await firstFunction()
  await secondFunction()
}

main()

Output I am getting is

second
first

Since there's an await for firstFunction(), I'd expect the promise of firstFunction() to finish before going to secondFunction().

Can someone point out why they ran in parallel and how to make them run one after the other? (ran in node v18.3.0)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to move your resolve() call inside setTimeout() function. Here is the fixed code:

function firstFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('first');
      resolve();
    }, 2000);
  });
}

function secondFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('second');
      resolve();
    }, 1000);
  })
}

async function main() {
  await firstFunction()
  await secondFunction()
}

main()

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