考虑以下代码:
矩形.js:
module.exports = (x,y,callback) => {
if (x <= 0 || y <= 0)
setTimeout(() =>
callback(new Error("Rectangle dimensions should be greater than zero: l = "
+ x + ", and b = " + y),
null),
2000);
else
setTimeout(() =>
callback(null, {
perimeter: () => (2*(x+y)),
area:() => (x*y)
}),
2000);
}
index.js:
var rect = require('./rectangle');
function solveRect(l,b) {
console.log("Solving for rectangle with l = "
+ l + " and b = " + b);
rect(l,b, (err,rectangle) => {
if (err) {
console.log("ERROR: ", err.message);
}
else {
console.log("The area of the rectangle of dimensions l = "
+ l + " and b = " + b + " is " + rectangle.area());
console.log("The perimeter of the rectangle of dimensions l = "
+ l + " and b = " + b + " is " + rectangle.perimeter());
}
});
console.log("This statement after the call to rect()");
};
solveRect(2,4);
solveRect(3,5);
solveRect(0,5);
solveRect(-3,5);
在这一行 rect(l,b, (err,rectangle)
中,我们调用 rect
函数并传递 l,b, err,rectangle
code> 到它。我可以看到什么是 l,b
,但无法看到和理解什么是 err,矩形
?
也无法理解callback
函数的定义在哪里?它是一个内部函数吗?
最佳答案
箭头表示法在这里可能会令人困惑,特别是因为它占用了大部分 rect
函数调用。它相当于
var callback = function(err,rectangle){
if(err) {
// do stuff
} else {
// do stuff
}
};
rect(l,b, callback);
当我们在index.js内部调用rect(l,b,callback)
时,它会调用矩形.js内部的函数,并传入对index.js中函数的引用(其中我在上面命名了回调)。这意味着当矩形调用 callback(new Error( ...
) 时,它会将 Error
对象传递给在 index.js 中定义的回调。当它调用 >callback(null, ...
它为 err 参数传递 null
,为 callback
中的矩形参数传递矩形对象。
目前,我们调用rect(l,b,callback)
,但我们没有 err 或矩形参数,javascript 只是知道它正在传递一个带有 2 个参数的函数。
关于javascript - NodeJS 中的回调函数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56408266/