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

133
Visualizações
How to make JS stack really "wait" for the ending of an asynchronous function?

I'm learning how Asynchronous JavaScript works, and I'm trying to print to the console the numbers 1 and 2 (in this order). The function that logs 1 has a setTimeout, and as such, the order is always inverted. I know why this happens. I just don't know how to make it work as I would like to. I've tried this:

function first(){
    setTimeout(
            ()=>console.log(1),
            1000
    )

    return Promise.resolve(true)
}

function second(){
    console.log(2)
}


function a(){
    first()
    .then(second())
}

console.log("running...")
a()

and also this:

async function first(){
    setTimeout( 
        ()=>console.log(1),
        2000
    )

    return true            
}

function second(){
    console.log(2)
}


async function a(){
    await first()
    second()
}

console.log("running...")
a()

Both of which print

running...
2
1

The desired output would be

running...
1
2

What am I doing wrong?

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

0

Would callbacks not be acceptable?

function first(callback) {
  setTimeout(() => {
    console.log(1);
    callback();
  }, 2000);
}

function second() {
  console.log(2)
}
// When first is completed, second will run.
first(() => second());
console.log("This can run at any time, while we're waiting for our callback.");

about 4 years ago · Juan Pablo Isaza Relatório

0

Read about Js promises (developer.mozilla.org) here his your code working

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

function second(){
    console.log(2)
}


async function a(){
    await first().then(res => console.log(res))
    second()
}

console.log("running...")
a()

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