Node.js - 回调概念


什么是回调?

回调是函数的异步等效项。完成给定任务时调用回调函数。Node 大量使用回调。Node 的所有 API 都是以支持回调的方式编写的。

例如,读取文件的函数可能会开始读取文件并立即将控制权返回到执行环境,以便可以执行下一条指令。一旦文件I/O完成,就会调用回调函数,同时向回调函数传递文件的内容作为参数。因此文件 I/O 不会发生阻塞或等待。这使得 Node.js 具有高度可扩展性,因为它可以处理大量请求,而无需等待任何函数返回结果。

阻止代码示例

创建一个名为input.txt的文本文件,其中包含以下内容 -

Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

使用以下代码创建一个名为main.js的 js 文件-

var fs = require("fs");
var data = fs.readFileSync('input.txt');

console.log(data.toString());
console.log("Program Ended");

现在运行 main.js 来查看结果 -

$ node main.js

验证输出。

Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended

非阻塞代码示例

创建一个名为 input.txt 的文本文件,其中包含以下内容。

Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

更新 main.js 以包含以下代码 -

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err) return console.error(err);
   console.log(data.toString());
});

console.log("Program Ended");

现在运行 main.js 来查看结果 -

$ node main.js

验证输出。

Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

这两个示例解释了阻塞和非阻塞调用的概念。

  • 第一个示例显示程序会阻塞,直到读取文件,然后才继续结束程序。

  • 第二个例子显示程序不等待文件读取并继续打印“Program Ended”,同时程序没有阻塞地继续读取文件。

因此,阻塞程序非常按顺序执行。从编程的角度来看,实现逻辑更容易,但非阻塞程序不是按顺序执行的。如果程序需要使用任何要处理的数据,则应将其保存在同一块中以使其顺序执行。