同一 node.js 程序中的异步和同步函数调用

Both asynchronus and synchronus function calls in the same node.js programme

在下面的nodejs程序中,input.txt里面只有一个字符串"abc"。

var fs = require("fs");
// Asynchronous read
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
 console.log("Asynchronous read: " + data.toString());
});

// Synchronous read

var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program Ended");

输出是

Synchronous read: abc
Program Ended
Asynchronous read: abc

现在,问题是,当程序开始执行时,它首先看到异步读取文件调用并在后台运行 'reading input.txt' 进程,然后服务器看到同步读取调用并再次开始读取input.txt。但是由于异步调用首先开始读取,当同步函数完成读取 .txt 时,异步函数的回调将被传递到事件循环并且应该首先执行..

所以输出的第一行应该是

Asynchronous read: abc

我哪里错了?

我认为程序正在遵循下一个行为。

1.- 开始异步读取文件。

2.- 立即开始同步读取同一文件(阻塞调用堆栈)。

3.- 在执行同步读取时,您的异步函数结束并将回调放在回调队列中,一旦调用堆栈空闲就会执行。

4.- 一旦同步函数和 console.log 语句结束(调用堆栈不再阻塞或忙碌),事件循环将队列上的回调移动到调用堆栈和执行异步回调。

我不是 100% 确定,但我基于这个解释,我认为有道理。

https://www.youtube.com/watch?v=8aGhZQkoFbQ

But as the asynchronous call has first started the reading, by the time the synchronous function completes reading the .txt, call back of of asynchronous function would have been passed to the events loop and should have been executed first..

强调的地方是误会的地方。回调被传递到回调队列,而不是事件循环。事件循环直到调用堆栈为空后才会循环,这在同步操作完成之前不会发生。

一旦调用堆栈为空,事件循环将运行,从回调队列中弹出一个回调,并执行它。这就是为什么异步回调发生在同步操作之后而不是之前的原因。

回调不能在执行同步动作时执行,因为在执行同步动作时,事件循环没有循环。

同步动作发生时,无法执行其他 javascript。