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

87
Visualizações
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 Respostas
Responde à pergunta

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 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