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

242
Visualizações
Proper use of async JS to ensure function calls wait for previous functions to complete (resolve?)

Trying to learn proper async/await JavaScript to run functions in sequence when an early function in the sequence would be delayed (using setTimeout to simulate). I'm not getting the expected results (still getting "first", "second", "this should run first?" - see code).

What am I missing? Do I have the wrong idea about this?

Thanks in advance!

const zeroFunction = () => {
    setTimeout(() => {
        return new Promise((resolve) => {
            console.log("This should run first?");
            resolve();
        }); 
}, 2000)}

const firstFunction = () => {
    return new Promise((resolve) => {
        console.log("first");
        resolve();
    }) 
}

const secondFunction = () => {
    return new Promise((resolve) => {
        console.log("second");
        resolve();
    })
}

async function fnAsync() {
    await zeroFunction();
    await firstFunction();
    secondFunction();
}

fnAsync();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

zeroFunction is currently returning undefined implicitly, not a Promise. Inverse the wrapping of the setTimeout and Promise constructor and it should work as expected.

const zeroFunction = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("This should run first?")
      resolve()
    }, 2000)
  })
}
const firstFunction = () => {
  return new Promise((resolve) => {
    console.log("first")
    resolve()
  })
}

const secondFunction = () => {
  return new Promise((resolve) => {
    console.log("second")
    resolve()
  })
}

async function fnAsync() {
  await zeroFunction()
  await firstFunction()
  secondFunction()
}

fnAsync()

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