Nodejs async

From wikinotes
Revision as of 14:55, 30 July 2021 by Will (talk | contribs) (→‎eventloop)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Like javascript, nodejs is single-threaded.
There are 2x ways things get executed in nodejs.

  • the call stack (last in, first out)
  • the queue (runs when call stack is empty)

See javascript async for more details.

async, promises, etc

See javascript async for more details.

const dostuff = () => {
  setTimeout(() => { console.log('hello') }, 0);
  console.log('foo');
}
  • setTimeout(..) enqueues a function execution after at least N seconds, once the call stack is empty.
  • console.log() adds a function to the call-stack, and it is executed right away

In this case, hello is printed AFTER foo, since the setTimeout is not executed until after dostuff() is removed from the call stack.

Timers and the Eventloop

My understanding (that may be incorrect) of callback execution is:

while true {
  setImmediateFunctions()    // setImmediate(fn)                       -- set in prev loop fn()
  expiredTimeoutFunctions()  // setTimeout(fn, 0), setInterval(fn, 0)  -- earliest set in prev loop fn() 
  regularFunction()          // fn()                                   -- until stack empty
  nextTickFunctions()        // process.nextTick(fn)                   -- set within same loop fn()
}