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

103
Visualizações
The execution sequence when returning a Promise object in promise then mehod

The code is:

Promise.resolve().then(() => {
    console.log(0);
    return Promise.resolve(4);
}).then((res) => {
    console.log(res)
})

Promise.resolve().then(() => {
    console.log(1);
}).then(() => {
    console.log(2);
}).then(() => {
    console.log(3);
}).then(() => {
    console.log(5);
}).then(() =>{
    console.log(6);
})

And the result is: 0 1 2 3 4 5 6.

Why log 4 is after log 3? What is the special thing happened when returning a promise object in .then method?

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

0

Javascript runs an event loop.

Here is my guess.

Promise.resolve() creates a promise which will be resolved in the next iteration. And every then block will be execute in the next iteration after the previous block finish. So here is the execution order:

Iteration 1: Created 2 promises (name them A and B) which will be resolved in Iteration 2

Iteration 2: Promise A resolves. Promise B resolves

Iteration 3: then block of Promise A executes, which prints 0 and creates a new promise (name it C) which will be resolved in Iteration 4. First then block of the Promise B executes, which prints 1.

Iteration 4: Second then block of Promise B executes, which prints 2. Promise C resolves. (Since Promise C is added to the event loop later than Promise B, Promise B resolves before Promise C)

Iteration 5: Third then block of Promise B executes, which prints 3. then block of Promise C executes, which prints 4.

Iteration 6: Forth then block of Promise B executes, which prints 5.

Iteration 7: Fifth then block of Promise B executes, which prints 6.

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