문제

I'm using "express" and "cradle" in "nodejs". If I request my database I have to define a callback to handle the response. Unfortunately I have no access to res (response) in my callback function. What is the best practice for this problem? Here is my code.

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?
  });
});
도움이 되었습니까?

해결책

You can just use res inside the inner callback.

In JavaScript the inner function "inherits" the variables of the outer function. Or more precisely, the function forms a closure, which is an expression that can have free variables. The closure binds the variables from its outer scope, which can be the scope of another function or the global scope.

다른 팁

You may try this.

Most important (perhaps your pitfall?) keep in mind that 'db.view' will mereley register a callback closure and continue. Do not close your request (by calling 'req.end') anywhere outside this closure. If you do, quite likely the request have been closed as the db returns. Once the http response object is closed any data written to it goes void.

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!!!
});

With this snippet you really should have access to res here. You should be able to use res.render() or res.send() because the db callback is wrapped in the closure of the app.get callback function.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top