gpt4 book ai didi

javascript - 如何使用bind传递对next()的引用?

转载 作者:行者123 更新时间:2023-12-02 16:01:10 24 4
gpt4 key购买 nike

我正在尝试概括一些模块代码,以便可以重用 Mongoose 回调函数。

我需要将对 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

最佳答案

bind 接受一个上下文,后跟一个参数列表。要将 next 作为第一个参数传递给绑定(bind)函数,您可以将其添加到 bind 的调用中:

// ...
userCreatedCallback.bind(null, next));

...并更新回调签名以支持它

function userCreatedCallback(next, err, user) {
// ...
}

但是,这与 Node 的 (err, ...) 连续传递风格读起来有点奇怪。使用像 async 这样的库可能有助于清理事情(more detail in an external blog post)。

关于javascript - 如何使用bind传递对next()的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31187982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com