-2
Promise.resolve()
.then(() => console.log(2))
.then(() => console.log(3));

Promise.resolve()
.then(() => console.log(4))
.then(() => console.log(5));

console.log(1);

why above code Snippet result is 1 2 4 3 5 instead of 1 2 3 4 5 .

what is the execution order?

Raghav Garg
  • 3,601
  • 2
  • 23
  • 32
  • Promises are asynchronous so this is likely a race condition. – cuuupid Sep 11 '17 at 20:13
  • 3
    the callback queue is fifo. 3 and 5 can't be inserted into the queue until after 2 and 4 run. – Kevin B Sep 11 '17 at 20:15
  • There is no specified order other then 1 will always be first, 3 will always follow 2 but not necessarily immediately,and 5 will always follow 4, again, not necessarily immediately. Welcome to asynchronous code ;) – phuzi Sep 11 '17 at 20:16
  • well, in this case it's pretty much guaranteed, but you'd be correct if this was an http request, or a db request, etc – Kevin B Sep 11 '17 at 20:17
  • the code is copied from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises with some my modifications. I understand const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); wait().then(() => console.log(4)); Promise.resolve().then(() => console.log(2)).then(() => console.log(3)); console.log(1); // 1, 2, 3, 4 cause they stated "Instead of running immediately, the passed-in function is put on a microtask queue, which means it runs later when the queue is emptied at the end of the current run of the JavaScript event loop " . – uonlyYOLOonce Sep 11 '17 at 20:25
  • `.then()` handlers are likely run in the order they were queued and the order yours are queued is 2, 4, 3, 5, though if your code depends upon a specific order, you SHOULD code to force that order and not rely on specific queuing strategies. – jfriend00 Sep 12 '17 at 00:23

1 Answers1

-2

It runs in this order because that's the order that the callbacks were entered into the callback queue.

Lets follow through what this code does:

Promise.resolve()
.then(() => console.log(2))
.then(() => console.log(3));

Promise.resolve()
.then(() => console.log(4))
.then(() => console.log(5));

console.log(1);
  • First, the main code is ran, two promises are created and resolved, and two callbacks are added to the callback queue; callbacks 2 and 4. The queue is now [2,4]. Then console.log(1) happens and the function ends.

  • Now that the function is done, the next callback in the callback queue runs, thus logging 2, that then pushes a new callback into the callback queue, callback 3. The queue is now [4,3].

  • Next, callback 4 runs and logs 4, and that pushes callback 5 into the queue. The queue is now [3,5]

  • Next, callbacks 3 and 5 each run in order, bringing the queue back to [].

If any of the functions were asynchronous, this order could have changed drastically based on how long each took to complete.

Kevin B
  • 94,570
  • 16
  • 163
  • 180