我在“ Nodejs”中使用“ Express”和“ Cradle”。如果我要求我的数据库,我必须定义回调以处理响应。不幸的是,我在回调功能中无法访问RES(响应)。这个问题的最佳实践是什么?这是我的代码。

var cradle = require('cradle');
var db = new cradle.Connection().database('guestbook');
app.get('/guestbook', function(req, res) {
  db.view('guestbook/all', function(err, doc) { 
    console.log(doc);
    // How can I use res in this callback
    // to send the response?
  });
});
有帮助吗?

解决方案

您可以使用 res 在内部回调中。

在JavaScript中,内部函数“继承”了外部函数的变量。或更确切地说,该函数形成闭合,它是可以具有自由变量的表达式。闭合结合了变量的外部范围,这可能是另一个函数或全局范围的范围。

其他提示

您可以尝试一下。

最重要的(也许是您的陷阱?)请记住,梅雷利(Mereley)会记录回调并继续。请勿在此关闭以外的任何地方关闭您的请求(通过调用'req.end')。如果您这样做,则很可能在数据库返回时已关闭请求。一旦关闭HTTP响应对象,任何编写的数据就会无效。

var cradle = require('cradle');
var db = new cradle.Connection().database('guestbook');
app.get('/guestbook', function(req, res) {
    // Register callback and continue..
    db.view('guestbook/all', function(err, guests) {
        // console.log('The waiting had an end.. here are the results');
        guests.forEach(function(guest) {
            if (guest.name) {
                res.write('Guest N: ' + guest.name);
            }
        });
        // Close http response (after this no more output is possible).
        res.end('That is all!')
    });
    console.log('Waiting for couch to return guests..');
    // res.end('That is all!'); // DO NOT DO THIS!!!
});

使用此片段,您确实应该可以在这里访问Res。你应该能够使用 res.render() 或者 res.send() 因为DB回调包裹在app.get回调函数的关闭中。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top