Nodejs async: Difference between revisions
From wikinotes
No edit summary |
(No difference)
|
Revision as of 22:46, 4 July 2021
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)
NOTE:
TL;DR nodejs async is essentially the same as javascript async
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 awayIn this case, hello is printed AFTER foo, since the setTimeout is not executed until after
dostuff()
is removed from the call stack.
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() }