📜  Node.js-回调概念

📅  最后修改于: 2020-11-03 10:05:08             🧑  作者: Mango


什么是回叫?

回调是函数的异步等效项。在完成给定任务时将调用回调函数。 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”,同时,该程序在不阻塞的情况下继续读取文件。

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