我有这样的路由器:
app.get('/rest/userList', (req, res) => {
UserList.find({}, (err, users) => {
if (err) res.send(err);
res.json(users);
});
});
我想改变它:
app.get('/rest/userList', getUsers);
function getUsers(req, res) {
UserList.find({}, createResponse);
}
function createResponse(err, users) {
if (err) return res.send(err);
return res.send(users);
}
然而;在createResponse函数' res'未定义。我怎么能这样做?
答案 0 :(得分:2)
您可以使用.bind()
将额外参数绑定到回调:
app.get('/rest/userList', getUsers);
function getUsers(req, res) {
UserList.find({}, createResponse.bind(null, res));
}
function createResponse(res, err, users) {
if (err) return res.send(err);
return res.send(users);
}
答案 1 :(得分:1)
app.get('/rest/userList', getUsers, createResponse);
function getUsers(req, res, next) {
UserList.find({}, function (err, users) {
if (err) {
req.errr = err;
} else {
req.users = users;
}
next();
});
}
function createResponse(req, res) {
if (req.err) return res.send(req.err);
return res.send(req.users);
}