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!!!!!

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

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

  • 第二个示例显示程序不等待文件读取并继续打印"程序结束",同时程序没有阻塞继续读取文件.

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