使用fs.readFile时有无错误的不同回调顺序

问题描述 投票:1回答:1

当我运行以下代码时

const fs = require("fs");

function sleep(ms) {
  let stop = new Date().getTime();
  while (new Date().getTime() < stop + ms) {}
}

function onRead(error, data) {
  console.log("in onRead");
}

function hello() {
  console.log("hello");
}

fs.readFile(__filename, onRead);

// Block 500ms to make sure the file is read
sleep(500);

console.log("hi");
setImmediate(hello);

打印

hi
hello
in onRead

到终端。

如果我将其更改为

const fs = require("fs");

function sleep(ms) {
  let stop = new Date().getTime();
  while (new Date().getTime() < stop + ms) {}
}

function onRead(error, data) {
  console.log("in onRead");
}

function hello() {
  console.log("hello");
}

// Now we are trying to read a non-existent file
fs.readFile("non-exist", onRead);

sleep(500);

console.log("hi");
setImmediate(hello);

打印

hi
in onRead
hello

什么使onReadhello的执行顺序不同?

node.js event-loop
1个回答
0
投票

fs.readFile是异步的,当nodejs完成读取文件并找到数据或返回错误时,将调用onRead。因此,很明显在console.log("hi")的结果可用之前调用fs.readFile。第二个输出取决于fs.readFile返回结果的速度。 fs.readFile在第一个方案中比在第二个方案中慢,因此这两个方案之间的第二个输出顺序有所不同。

这也与NodeJs事件循环如何执行其阶段有关。

这些关于NodeJs事件循环执行顺序的文章包含很多信息The Node.js Event Loop, Timers, and process.nextTick()Understanding the Node.js event loop phases

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.