0

在 mongojs 中,当你这样做时:

var birds = db.birds.find(searchTerm, callback);

...你如何将参数传递给回调?我试过绑定,如:

birds = db.birds.find(searchTerm, app.get('getBirds').bind(res));

……但无济于事。仅供参考,我正在尝试传递 GET 路由的响应对象,以便回调可以使用 res.send(results) 呈现。

另一个选项是设置 app.set('res': res); 并从回调中调用 app.get('res') - 我不确定这是一个好主意。它可以工作,但它不能很好地遵守事件循环模型 - 我认为返回应用程序的请求可能代价高昂?任何帮助将不胜感激。:)

4

2 回答 2

1

确定您要完成的工作:

您是否打算find在服务器的响应中使用调用结果?您可以将 包装find在一个将响应作为参数接收的函数中,然后定义对 的回调,并在find其中访问响应。

例如(未经测试的代码,但这是想法):

// function called when a request is received
function getBirds(searchTerm, res) {
    birds = db.birds.find(searchTerm, function(err, docs) {
        // code in here will have access to res because it is in a closure
    });
}
于 2012-11-01T16:32:11.007 回答
0

您通常通过将callback函数调用包装在匿名函数中来做到这一点:

db.birds.find(searchTerm, function (err, birds) {
    callback (err, birds, res);
});
于 2012-11-01T16:57:46.867 回答