Thursday 14 June 2018

Help me understand event loop better

Hey! I was reading this https://ift.tt/2jMw5hm dock and found this table ┌───────────────────────────┐ ┌─>│ timers │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ pending callbacks │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ idle, prepare │ │ └─────────────┬─────────────┘ ┌───────────────┐ │ ┌─────────────┴─────────────┐ │ incoming: │ │ │ poll │<─────┤ connections, │ │ └─────────────┬─────────────┘ │ data, etc. │ │ ┌─────────────┴─────────────┐ └───────────────┘ │ │ check │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ └──┤ close callbacks │ └───────────────────────────┘ And description:Phases Overview * timers: this phase executes callbacks scheduled by setTimeout() and setInterval().pending callbacks: executes I/O callbacks deferred to the next loop iteration.idle, prepare: only used internally.poll: retrieve new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and setImmediate()); node will block here when appropriate.check: setImmediate() callbacks are invoked here.close callbacks: some close callbacks, e.g. socket.on('close', ...).If i understand correctly, callbacks should be invoked in ordertimers(setTimeout in my case)regular callbacks(promises too)setImmediate callbackson('close') callbacksBut when i run this code'use strict'; let dataHolder = null; const someAsyncFn = () => Promise.resolve({ data: 42 }); someAsyncFn().then((data) => dataHolder = data); console.log('Just data:', dataHolder); process.nextTick(() => console.log('process.nextTick:', dataHolder)); setTimeout(() => console.log('setTimeout:', dataHolder), 0); setImmediate(() => console.log('setImmediate:', dataHolder)); I get resultsJust data: null process.nextTick: null setTimeout: { data: 42 } setImmediate: { data: 42 } This the part i don't get. Everything makes sense, but the part when is executed after promise callback. Should not setTimeout be executed before promise callback, based on the table above(timers go first and then pending callbacks)?Thanks!

Submitted June 14, 2018 at 03:26PM by SandOfTheEarth

No comments:

Post a Comment