GroovyBoba
GroovyBoba
24mo

event loop

code: const fs = require('fs') fs.readFile('./abc.txt', (err, data) => { console.log('read file finished') }) process.nextTick(() => console.log('process.nextTick callback')) setImmediate(() => { console.log('setImmediate callback') }) setTimeout(() => { console.log('setTimeout callback') }, 0) Promise.resolve().then(() => console.log('Promise resolved'))

output: process.nextTick callback Promise resolved setTimeout callback setImmediate callback read file finished

Can someone explain this in detail?

24mo ago
PrancingNoodle
PrancingNoodle
24mo

JS use execution queue for async processing. What I see is process.nextTick have highest priority and is processed immediately followed by Promise resolved. SetTimeout guarantee that it will execute after this given amount of time basically lower limit is fixed but upper limit is not. Read file is IO operation and it is slowest of all.

Discover more
Curated from across