【发布时间】:2019-10-17 21:09:24
【问题描述】:
考虑以下代码:
矩形.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 传递给它。我可以看到l,b 是什么,但看不到和理解err, rectangle 是什么?
也看不懂callback函数的定义在哪里?是内部函数吗?
【问题讨论】:
-
callback是rect函数的参数,其值是您作为参数提供的(err, rectangle) => ...函数。 -
这与
x和y从函数参数中获取的方式没有什么不同。 -
err和rectangle是index.js中匿名函数的参数。 -
当您在 rectangle.js 中调用回调时,您正在传递这些参数。
-
也许你不明白箭头函数符号?
(err, rectangle) => {...}类似于function(err, rectangle) {...}
标签: javascript node.js error-handling callback