我有一个路由,它做了一些处理,而不是返回回调。 这是代码:
router.get('/login', function(req,res,next) {
// send call to login function.
var ID= req.query.ID;
var Password = req.query.Password
ctlLogin.login(ID,Password, LoginCallback);
});
function LoginCallback(err,myLoginResult)
{
res.json(myLoginResult);
}
登录函数检查数据库中是否存在用户/密码并返回:
loginCallback(result);
我的问题 - LoginCallBack 函数不知道对象 res。 我知道我可以将它传输到登录模块,只是将其作为回调函数的参数传回给我,但这似乎是一个糟糕的设计,我需要将回调函数发送到登录方法,这已经足够糟糕了。
有没有更好的方法来做到这一点,并且仍然具有可读的代码?
最佳答案
我在你的情况下使用的解决方案(如果我们跳过使用 promise 和其他更难的东西)是将函数绑定(bind)到上下文。 大多数情况下,它用于在使用对象方法作为回调时保留对象上下文,但它也可用于创建参数少于原始函数的函数(有时称为柯里化(Currying))。
在 javascript 中,您可以在任何函数上使用方法 bind
绑定(bind)上下文。第一个参数是函数调用时的this
值,其他参数只是参数值。
您的代码使用bind
重写:
router.get('/login', function(req,res,next) {
// send call to login function.
var ID= req.query.ID;
var Password = req.query.Password
ctlLogin.login(ID,Password, LoginCallback.bind(null, res));
});
function LoginCallback(res, err, myLoginResult)
{
res.json(myLoginResult);
}
```
关于javascript - Node.js 回调设计 - 如何在回调中使用 res,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840213/