如何在自己的函数中定义一个callback函数? 的NodeJS

我在nodeJS中很新,出现了以下问题:我在我的一个控制器中定义了一个函数,我想validation一个JSON-Web-Token。 我使用了以下function:

exports.validate = function (token, cb) { jwt.verify(token, secretToken, cb(err, decoded)); } 

但每次我想运行它,nodeJS给我的错误,'err'没有定义? 在jwt-Example中有以下例子:

 // verify a token symmetric jwt.verify(token, 'shhhhh', function(err, decoded) { console.log(decoded.foo) }); 

所以显然我错了,但我不知道是什么。 我也不知道要寻找什么…我做了一些谷歌search,但没有任何帮助我到目前为止。

我很乐意听取您的意见。

问候

/ /编辑:这就是我所说的function:

 AuthController.validate(req.headers['api-token'], function(err, decoded){ if(err){ console.log('Error: ', err); res.status(401); next(); } else if(decoded) { console.log('Success: ', decoded); next(); } }) 

如果你想让你的函数使用callback函数,应该这样使用它:

 exports.validate = function (token, cb) { jwt.verify(token, secretToken, function (err, decoded) { if (err) return cb(err, null); // callback have to handle error return cb(null, decoded); } } 

在jwt-Example中, verify的第三个参数是一个函数 (使用函数expression式创build)。

在你的代码中,第三个参数是返回值或调用cb(err, decoded)cb函数可能会返回一个函数,但是err是您传递它的variables。

如果你想使用一个叫做cb的函数,那么定义它,然后传递函数:

 function cb(err, decoded) { // do stuff with err and/or decoded } jwt.verify(token, secretToken, cb);