Node.js 回调处理程序通常传递给的第一个参数是什么
Node.js中的回调处理程序函数是处理特定操作完成后的一种方式。这是处理异步代码的一种方式,这些代码需要很长时间才能产生结果,因此我们可以调用回调处理程序并传递任何错误以及异步操作的结果。
回调处理程序函数遵循错误优先的约定:
- 回调处理程序的第一个参数应该是错误,第二个参数可以是操作的结果。
- 在调用回调函数时,如果出现错误,我们可以这样调用: callback(err) 否则,我们可以这样调用: callback(null, result) 。
语法:
const func = (arg1, agr2, ..., argN, callback) => {
// code logic
}
func(a, b, ..., n, (err, result) => {
// code logic
})
项目创建
步骤1: 安装Node.js,如果你还没有安装的话。
步骤2: 为你的项目创建一个文件夹,并进入该文件夹(使用cd命令)。在该文件夹内创建一个名为app.js的新文件。现在,使用以下命令初始化一个新的Node.js项目,并使用默认配置。
npm init -y
项目结构: 在按照以下步骤之后,您的项目结构将如下所示。
示例: 在下面提到的代码示例中,我们创建了一个执行除法操作的函数。为了模拟异步操作,我们使用了setTimeout()方法,该方法在一秒钟后调用回调处理程序。当除数为零时,回调处理程序以错误实例作为唯一参数进行调用,否则回调以null作为第一个参数,以除法结果作为第二个参数进行调用。
app.js
const divide = (a, b, callback) => {
setTimeout(() => {
if (b === 0) {
callback(new Error('Division by zero error'));
} else {
callback(null, a / b);
}
}, 1000);
};
// Our callback handler expects error
// as first argument and the result
// of division as second argument.
divide(5, 2, (err, result) => {
// We check if the error exists then we
// print the error message and return
if (err) {
return console.log(err.message);
}
// We print the result if there is no error
console.log(`The result of division is {result}`);
});
// In this cases our callback handler
// will be called with an error Instance
// as the divisor is zero
divide(5, 0, (err, result) => {
if (err) {
return console.log(err.message);
}
console.log(`The result of division is{result}`);
});
运行应用程序的步骤: 您可以在命令行上使用以下命令来执行您的app.js文件。
node app.js
输出: