Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the response in callback functions (used by cradle in nodejs for example)

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?
  });
});
like image 940
koalabruder Avatar asked Mar 14 '11 20:03

koalabruder


2 Answers

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.

like image 110
alienhard Avatar answered Nov 15 '22 07:11

alienhard


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!!!
});
like image 22
Torbjörn Österdahl Avatar answered Nov 15 '22 08:11

Torbjörn Österdahl