Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!