Я пытаюсь обобщить некоторый код модуля, чтобы я мог повторно использовать функцию обратного вызова Mongoose.Как использовать bind для передачи ссылки на next()?
Мне нужно передать ссылку на функцию next() на обратный вызов, чтобы обратный вызов мог вызвать его, если он был успешным.
Вот что мой код выглядит в настоящее время:
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);
});
}
};
Я также попытался userCreatedCallback.bind({ next: next })
, но это также не удается. Ошибка я получаю:
<project-dir>/node_modules/mongoose/node_modules/mpromise/lib/promise.js:108
if (this.ended && !this.hasRejectListeners()) throw reason;
^
ReferenceError: next is not defined
Я бы recomment '.bind (null, next)' хотя. В противном случае он привязан к модулю, который не выглядит очень полезным. – Bergi
Что сказал @Bergi. Это предпочтительное использование связывания. –
Отличная точка-обновление ответа. – rjz