const fs = require("fs");
const dns = require("dns");
function timeStamp() {
return performance.now().toFixed(2);
}
console.log("Start");
//Close events
fs.writeFile("./test.txt", "Hello man", () =>
console.log("Written done", timeStamp())
);
//Promises
Promise.resolve().then(() => console.log("Promise 1", timeStamp()));
//Tick
process.nextTick(() => console.log("Tick 1", timeStamp()));
//setImediate (Check)
setImmediate(() => console.log("Immediate 1", timeStamp()));
//Timeouts
setTimeout(() => console.log("Timeout 1", timeStamp()), 0);
setTimeout(() => {
process.nextTick(() => console.log("Tick 2", timeStamp()));
console.log("Timeout 2", timeStamp());
}, 10);
// I/O events
dns.lookup("localhost", (err, address, family) => {
console.log("DNS 1 localhost", address, timeStamp());
Promise.resolve().then(() => console.log("Promise 2", timeStamp()));
process.nextTick(() => console.log("Tick 3", timeStamp()));
});
console.log("End");
const fs = require("fs");
async function main() {
console.log("Start");
setTimeout(() => console.log("SetTimeout"), 0);
setImmediate(() => console.log("SetImmediate"));
Promise.resolve().then(() => {
console.log("Promise");
process.nextTick(() => console.log("Promise next tick"));
});
fs.readFile("idex.js", () => {
console.log("Read file");
setTimeout(() => console.log("Read file SetTimeout"));
setImmediate(() => console.log("Read file SetImmediate"));
process.nextTick(() => console.log("Read file next tick"));
});
const response = await Promise.resolve("Async/Await");
console.log(response);
process.nextTick(() => console.log("Next tick"));
setTimeout(() => console.log("SetTimeout"), 0);
console.log("End");
}
main();
I have a few questions.
Why do files have different order of promise output if they are written the same way?
The second question is, why does my VSC display this order in the second file, if according to the rules and documentation the order should be completely different?
Start,
Promise,
Async/Await,
End,
Promise next tick,
Next tick,
SetTimeout,
Read file,
Read file next tick,
SetImmediate,
Read file SetImmediate,
SetTimeout,
Read file SetTimeout
The third question is why the order of output in the first file is constantly changing and is the operation of writing to the file a closing operation?
Start,
End,
Tick 1 47.94,
Promise 1 48.03,
Timeout 1 48.46,
Immediate 1 49.02,
Written done 49.39,
DNS 1 localhost ::1 50.54,
Tick 3 50.66,
Promise 2 50.79,
Timeout 2 63.08,
Tick 2 63.23
Start,
End,
Tick 1 40.30,
Promise 1 40.40,
Timeout 1 40.71,
Immediate 1 41.19,
DNS 1 localhost ::1 42.63,
Tick 3 42.80,
Promise 2 42.94,
Written done 43.12,
Timeout 2 47.94,
Tick 2 48.08,
Sometmes Immediate 1 is below DNS.
And lastly, please write which order in both options would be correct and why.
I watched dozens of videos, there are different explanations everywhere, I don’t offer documentation, I’m still too inexperienced for it.