繁体   English   中英

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的第二个参数,这是errfoundCampground未在任何地方定义,因为它是...一个函数的定义的参数

如果您不熟悉parameterargument之间的区别。

参数是函数声明中的变量。 Arguments是传递给该参数的函数的实际值。

例如:

req.headers.bodyfunction (err, foundCampground){ ... }是一个Argument

同时errfoundCampground是一个参数。

至于,什么arguments会被传递给errfoundCampground 这将由逻辑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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM