K
K
komigor2021-03-25 14:34:31
Node.js
komigor, 2021-03-25 14:34:31

Why does the Event Loop skip the poll queue and do a check right away?

Why does the Event Loop skip the poll queue and do a check right away? It's not logical that he executes all the queues in order, and then bam and jumps. That's why and for what is not clear.

For example, in this code, it will first go and execute setImmidiate instead of readFile

const fs = require('fs');

console.log('START');
 
setTimeout(() => console.log('setTimeout'), 0); //Попал в очередь timers 1)timers  set intervals  
setImmediate(() => console.log('setImmediate')); //Попал в очередь check 7


fs.readFile( 'eventloop.txt', () => { //попл в очередь poll
    setTimeout(() => console.log('readfile setTimeout'), 0);
    setImmediate(() => console.log('readFile setImmidiate'));
    process.nextTick(() => console.log('read file Next Tick'));
    }
)

Promise.resolve() // Попал в очередь other microtask que
            .then(() => {
                console.log('Promise')
                process.nextTick(() => console.log('Promise Next Tick'));
            })
            
            process.nextTick(() => console.log('nextTick'));
     
         setTimeout(() => console.log('setTimeout 2'), 0); //Попал в очередь timers 1)timers  set intervals  все node.js пропарсилась;
console.log('end')


Here is the log

START
end
nextTick
Promise
Promise Next Tick
setTimeout
setTimeout 2
setImmediate
read file Next Tick
readFile setImmidiate
readfile setTimeout

and why is it like this and not like this

START
end
nextTick
Promise
Promise Next Tick
setTimeout
setTimeout 2
read file Next Tick
readFile setImmidiate
readfile setTimeout
setImmediate

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
komigor, 2021-03-25
@komigor

It turned out that accessing the file system Node.js delegates to system calls, that is, this phase is not completely under the control of Node.js, unlike all the others in my script. Therefore, until a response from the file system arrives, the event loop may go through a coil or more.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question