0

Why the output result is "1, 2, 3, 4", not "1,4,2,3"?

If you have a answer, pls give a separate answer below, not a comment, explaining which run of the JavaScript event loop do which thing is appreciated,such as:

(1)..

(2)..

(3)..

Thanks!

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

wait(0).then(() => console.log(4));
Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
console.log(1); // 1, 2, 3, 4
Ethan
  • 165
  • 1
  • 9
  • 2
    Why do you invoke `wait` without the mandatory argument? – zerkms Aug 24 '17 at 01:34
  • Because `.then()` handlers on an already resolved promise are called before `setTimeout()` handlers. – jfriend00 Aug 24 '17 at 01:41
  • asynchronous code is asynchronous - if your intent is to somehow be able to predict the order of asynchronous code, then you have a better chance of staying dry whilst peeing into the wind :p – Jaromanda X Aug 24 '17 at 01:57
  • I have changed wait() to wait(0). the time is not important, and the result is same. – Ethan Aug 24 '17 at 08:38

0 Answers0