1

My answer is 0 1 2 3 5 6 4, but the output in Chrome is 0 1 2 3 4 5 6, I have read Tasks, microtasks, queues and schedules and I tried to understand the order of Promise, I think I did it.

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)
  })
jfriend00
  • 683,504
  • 96
  • 985
  • 979
frank
  • 21
  • 1
  • 3
    This is two completely separate and independent promise chains. The relative order between the two separate promise chains should NEVER be relied upon since any real code would have real asynchronous operations which would be entirely unpredictable for when they would resolve their promises. Moral of the story: If you care about the detailed timing between two promise chains, then link the two promise chains so you can control exactly what happens when. – jfriend00 Nov 27 '21 at 03:12
  • 3
    In other words, there's little practical use to try to understand this. That level of understanding would never be useful in real code or necessary in real code. Purely academic curiosity, I guess. – jfriend00 Nov 27 '21 at 03:12
  • It must be promise internals that wrap around the internal promise. So there's a "hidden" `then` in which the promise created by the first `then` assumes the state of the inner promise and that ends up shifting its place in the loop. – MinusFour Nov 27 '21 at 03:45
  • 1
    @jfriend00 Not forgetting to mention that details such as this may even change when optimisations are introduced in the spec – Bergi Nov 27 '21 at 05:39
  • @Bergi - Yep. As we've seen happen before. – jfriend00 Nov 27 '21 at 06:08

0 Answers0