Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How promise callbacks are scheduled vs setTimeout, by JS engines or browser/Node external API?

I am considering entire JS environment in two different parts in the question.

  1. JS engine
  2. Browser API, Node API (External to JS engine).

JavaScript engines(V8, SpiderMonkey) are single threaded and prior to ES6 there was no mechanism to run async code in JavaScript until ES6 introduced Promise concept.

I understand before promises came in, browsers or Node API(Server side JS) used to provide mechanism to run the code asynchronously using setTimeout and Process.nextTick and since Promises are natively supported to run async code in Javascript, I am trying to understand how promise callbacks and setTimeout are scheduled to run one before another.

Does this mean there are two event loops exists and they coordinate with each other? first in Browser/Node API to run code from setTimeout and Process.nextTick and another in JS engines to run promise callbacks, if no then how they are scheduled as there is no presence of setTimeout and Process.nextTick definition inside JS engines but Promise definition must be present in JS engines as Promise is ES6 standard.

Also I want to understand where is the task queue, job queue, mircotasks are present and managed, Inside JS engines or outside engine(in browsers or Node API).

like image 420
Akshay Naik Avatar asked Oct 17 '22 21:10

Akshay Naik


1 Answers

the main two js runtime engine:

  • browser
  • nodejs(V8)

in the browser(google browser):

javascript event-loop in browser

MacroTask:

  • setTimeout
  • setInterval

MicroTask:

  • Promise

execution sequence:

Promise> Promise.then> setTimeout

in nodejs runtime:

nodejs event-loop

microtasks:

  • process.nextTick
  • promise

macrotasks:

  • setTimeout
  • setInterval
  • setImmediate
  • I/O

execution sequence:

promise> process.nextTick> promise.then > setImmediate> setTimeout

lots of articles about event-loop. give you some refs to help you know about the theory:

  • How JavaScript works: Event loop and the rise of Async programming + 5 ways to better coding with async/await
  • event-loop
  • event-loop-timers-and-nexttick
like image 143
dukegod Avatar answered Oct 31 '22 21:10

dukegod