0

I got some problems in javascript's event loop.

I run the following code

setTimeout(function() {
    console.log('setTimeout1');
      Promise.resolve().then(function() {
        console.log('promise1');
      }).then(function() {
        console.log('promise2');
      })
  }, 0);
  setTimeout(function() {
    console.log('setTimeout2');
      Promise.resolve().then(function() {
        console.log('promise3');
      }).then(function() {
        console.log('promise4');
      })
  }, 0);

I get different ouput in node and browser.

node's output:

setTimeout1
setTimeout2
promise1
promise3
promise2
promise4

browser's output:

setTimeout1
promise1
promise2
setTimeout2
promise3
promise4

I can't figure it out.

Suen
  • 9
  • 2
  • 3
    The implementation of when a asynchronous call runs will vary. Why is this a problem? this smells of an XY problem. If you want something to run in a particular order then you need to code it so that it runs in that order. Relying on timings is a bad idea. – Liam Jul 25 '18 at 09:35
  • also see [Is there a more accurate way to create a Javascript timer than setTimeout?](https://stackoverflow.com/questions/196027/is-there-a-more-accurate-way-to-create-a-javascript-timer-than-settimeout) – Liam Jul 25 '18 at 09:38

0 Answers0