2

Output: 5, 4, 1, 3, 2. Why?Process.nexttick was supposed to add callbacks to the queue at the next point in time and should take precedence over promise.then, but why didn't that happen? NextTick was executed last and my expectation was 5, 3, 4, 1, 2. What did I miss?

    setTimeout(() => {
      process.nextTick(() => {console.log(2)})
      console.log(1)
    }, 0)
    new Promise(resolve => {
      resolve()
    }).then(() => console.log(4))
    process.nextTick(() => {console.log(3)})
    console.log(5)```
minHao
  • 31
  • 2
  • 3
    Promises use a [microtask queue](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth#Tasks_vs_microtasks), which is handled at a "higher priority" (not really, but lets think of it that way) than the standard task queue in javascript – Jaromanda X Nov 10 '20 at 05:18
  • What happens when I run in Node is completely different than what happens when I run on React, God,why? – minHao Nov 10 '20 at 05:33
  • 1
    because react is in the browser, and `process.nextTick` doesn't exist in a browser - perhaps? – Jaromanda X Nov 10 '20 at 05:44
  • Finally understand. The browser's Event loop is different from Node's Event loop, which means they use a different JS specification – minHao Nov 10 '20 at 07:16
  • The event loop is not a JS thing. In a browser, [html](https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model:event-loop) does define how the event loop works. And for why your environment outputs the way it does, we need to see how it did implement process.nextTick. – Kaiido Nov 10 '20 at 07:38
  • 1
    you were on a roll until you said `they use a different JS specification` - no, they don't use a different JS specification ... modern browsers and nodejs use the SAME specification - it's called ECMA 262 or ECMAScript Language Specification – Jaromanda X Nov 10 '20 at 07:43
  • `process` is non-standard and is not part of any JS specification. Thus `process.nextTick` is also non-standard and does not have to conform to any standard – slebetman Nov 10 '20 at 08:04
  • Weirdly, a lot of things we are used to in js are non-standard. For example `console.log()` is 100% proprietary but all implementers decided to call their logging function `console.log` – slebetman Nov 10 '20 at 08:05
  • @slebetman Actually [`console` got standardised](https://console.spec.whatwg.org) as well. Not certain if node conforms to that standard, though – Bergi Nov 10 '20 at 08:07

0 Answers0