I was reading about the node's event loop phases, and says that
- 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', ...).
So here i have a simple code to test some od the phases above. When you execute the code you get this ouput:
- close
- immediate
- timeout
But sockets callbacks as per doc, are last in the phases. Why it is executed first?
let socket = require("net").createServer();
socket.on("data", function (data) {
console.log(data.toString());
});
socket.on("close", function (data) {
console.log("close");
});
socket.listen(8080);
const fs = require("fs");
fs.readFile("readme.txt", () => {
socket.close();
setTimeout(() => {
console.log("timeout");
}, 0);
setImmediate(() => {
console.log("immediate");
});
});