Javascript 回调函数参数
我一直在学习Node.js教程。我一直怀疑数据是如何传递给回调函数参数的。例如Javascript 回调函数参数,javascript,node.js,Javascript,Node.js,我一直在学习Node.js教程。我一直怀疑数据是如何传递给回调函数参数的。例如 User.addUser(newUser, (err, user) =>{ if(err){ res.json({success: false, msg:'Failed to register new user'}); } else { res.json({success: true, msg:'User registered'}); } }); add
User.addUser(newUser, (err, user) =>{
if(err){
res.json({success: false, msg:'Failed to register new user'});
} else {
res.json({success: true, msg:'User registered'});
}
});
addUser函数定义为
module.exports.addUser = function(newUser, callback){
bcrypt.genSalt(10, (err,salt)=>{
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUser.password = hash;
newUser.save(callback);
});
});
}
我不明白err和user是如何传递的。有人能解释一下吗?答案是
newUser.save
还接受回调
参数,并将相同类型的参数传递给它。因此,您可以直接将回调传递到save。我想象user.save
的外观如下所示:
User.prototype.save = function(callback) {
//do stuff to save the user
//maybe get an error in the process, or a user record, pass them to the callback
callback(saveError, userRecord)
}
由于save
和addUser
的预期参数相同,因此可以直接将回调传递到save
编辑:
但是,如果bcrypt调用返回回调,我建议调用带有错误的回调。因为您已经有了一个回调来给出错误,所以抛出回调没有多大意义。调用者预计回调中会出现错误,因此我建议改为:
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) {
callback(err, null)
return
}
...
他们不是从这里经过的。它们从
newUser.save中传递。您只是将回调传递给该函数,该函数可能最终会调用它。“因为save和addUser的预期参数相同,所以回调可以直接传递到save中。”user.save方法和addUser都希望回调,其中err
是第一个参数,user
是第二个参数。因此,传递给addUser的回调可以直接传递给user.save,因为两者都需要相同的回调参数。