[英]How is this callback working in this code?
I am confused how cb(); 我很困惑cb(); is working? 正在工作? What does it do? 它有什么作用?
beforeCreate: function(user, cb) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {
console.log(err);
cb(err);
} else {
user.password = hash;
cb();
}
});
});
}
Assuming I understand your question, what you're probably not understanding is that cb
isn't defined in your sample - it's a reference to something that will be passed in as a parameter to beforeCreate
. 假设我了解您的问题,您可能不了解的是示例中未定义cb
,它是对将作为参数传递给beforeCreate
。
Assuming you have your code above you would then, at some point, call beforeCreate
and pass into it a method (callback) that will be used inside - like this 假设您在上面有代码,那么在某个时候,您将调用beforeCreate
并将一个将在内部使用的方法(回调)传递给它-像这样
beforeCreate({name:"Joe"}, /* user */
function(err){ /* callback */
if(err) return console.log("beforeCreate callback has been called with error" + err); /* check if there is error and return from function */
console.log("beforeCreate called successful") /* otherwise called succesfull */
}
)
So... that anonymous function in there (after the / callback / comment is the callback that you're passing in (as a reference) to beforeCreate
and what you *do with it is defined IN beforeCreate
(above in your example). 所以...那里的匿名函数(在/ callback /注释之后是您要传递(作为参考)到beforeCreate
的回调,并且您使用*所做的操作是在beforeCreate
定义的(在示例中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.