Why setImmediate() execute before fs.readFile() in Nodejs Event Loop's works?

前端 未结 2 817
渐次进展
渐次进展 2020-12-03 13:10

I have read a lot of related documents.But I still can\'t understand how it works.

const fs = require(\'fs\')
const now = Date.now();

setTimeout(() =>         


        
2条回答
  •  执念已碎
    2020-12-03 13:24

    setTimeout(() => console.log('timer'), 10);                
    fs.readFile(__filename, () => console.log('readfile'));    
    setImmediate(() => console.log('immediate'));               
    
    while(Date.now() - now < 1000) {
    }
    

    Explanation

    1. The setTimeout schedules to be put in an event loop after 10ms.

    2. Asynchronous file reading starts.

    3. The non-standard setImmediate schedules to show a console output breaking long processes.

    4. A one-second blocking loop runs. Nothing in the console yet.

    5. setImmediate prints immediate console message during the loop.

    6. File reading ends and the callback is executed even after the while loop is over. The console output readfile is there now.

    7. Finally, the console message timer is printed after about 10 secs later.

    Things to note

    • None of above commands (except the loop) are synchronous. They schedule something and immediately proceed to the next command.

    • The callback functions are called only after the current blocking execution is over.

    • Timeout commands are not guaranteed to be executed at the designated interval. The guarantee is that they will run anytime after the interval.

    • setImmediate is very experimental.

提交回复
热议问题