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

106
Vistas
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 Respuestas
Responde la pregunta

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