[英]How deal with the parameter 'error' in a call back function in node.js?
[英]argument of Node.js's call back function
下面的代码使用 node.js 和 mongoose 创建一个 GET 路由。 在 findById 函数中,我们使用了一个回调函数,它接受 err 和 foundCampground。 我将回调函数解释为某种高阶函数,但是如何传递包含参数的函数? findById 执行时,传递给回调函数的变量是什么? 我问这个是因为错误,并且 foundCampground 没有在其他任何地方定义,所以我不知道在执行过程中应该传递给回调函数的内容。
app.get("/campgrounds/:id", function(req, res){
Campground.findById(req.params.id, function(err, foundCampground){
if(err){
console.log(err);
}
res.render("show", {campground: foundCampground});
});
});
该参数Campground.findById的第二个参数,这是err
和foundCampground
未在任何地方定义,因为它是...一个函数的定义的参数。
如果您不熟悉parameter和argument之间的区别。
参数是函数声明中的变量。 而Arguments是传递给该参数的函数的实际值。
例如:
req.headers.body
和function (err, foundCampground){ ... }
是一个Argument 。
同时err
和foundCampground
是一个参数。
至于,什么arguments
会被传递给err
和foundCampground
? 这将由逻辑Campground.findById
处理
这是一个示例,说明如何编写自己的接受回调的函数
const items = [{ id: 1, name: 'Adam' }, { id: 2, name: 'Ramadoka' }, ];
function findById(searchedId, callback){
// the 2nd argument is a callback function, that we will call
// by passing error (if not found) as the first argument (or null otherwise)
// and the item (if the item is found) as the 2nd argument (or null otherwise)
for (const item of items) {
if(item.id === searchedId) {
return callback(null, item);
}
}
return callback(new Error('not found'), null);
}
// and then you can call it with something like:
findById(2, function (error, item) {
if (error) { console.error(error); }
if (item) { console.log(item); }
});
我希望它有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.