Javascript 如何使用bind传递对next()的引用?
我试图概括一些模块代码,以便可以重用Mongoose回调函数 我需要将对next()函数的引用传递给回调函数,以便回调函数可以在成功时调用它 以下是我的代码当前的样子:Javascript 如何使用bind传递对next()的引用?,javascript,node.js,express,mongoose,Javascript,Node.js,Express,Mongoose,我试图概括一些模块代码,以便可以重用Mongoose回调函数 我需要将对next()函数的引用传递给回调函数,以便回调函数可以在成功时调用它 以下是我的代码当前的样子: module.exports = { createUser: function (req, res, next) { // Make accessing the request body shorter var data = req.body; // Create th
module.exports = {
createUser: function (req, res, next) {
// Make accessing the request body shorter
var data = req.body;
// Create the user
User.create({
email: data.email,
password: data.password,
gender: data.gender,
firstname: data.firstname,
lastname: data.lastname
},
userCreatedCallback.bind(this)); // <-- this is where I want to pass in the reference to next()
}
};
function userCreatedCallback(err, user) {
if (err) {
// Handle error
}
} else {
// Create a Thing for the user
Thing.create({
name: user.fullname + '\'s thing',
createdBy: user._id
}, function(err, thing) {
// Call the next middleware
next(err);
});
}
};
bind
获取一个上下文,后跟一个参数列表。要将next
作为第一个参数传递给绑定函数,可以将其添加到调用bind
:
// ...
userCreatedCallback.bind(null, next));
。。。并更新回调签名以支持它
function userCreatedCallback(next, err, user) {
// ...
}
然而,对于节点的
(err,…)
继续传递样式,这读起来有点奇怪。使用类似的库可能有助于清理()。我建议编译.bind(null,next)
。否则它会绑定到模块,这看起来不是很有用。这是bind的首选用法。
function userCreatedCallback(next, err, user) {
// ...
}