How to handle the response in callback functions (e.g. used by stand in nodejs)

I use "express" and "cradle" in "nodejs". If I query my database, I have to define a callback to handle the response. Unfortunately, I do not have 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? }); }); 
+6
callback io couchdb express
source share
3 answers

You can just use res inside an internal callback.

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

+10
source share

You can try this.

Most importantly (maybe your trap?) Remember that "db.view" will mereley register a callback closure and continue. Do not close your request (by calling 'req.end') anywhere outside of this close. If you do this, most likely the request will be closed by db return. When the HTTP response object is closed, any data written to it loses its validity.

 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!!! }); 
+3
source share

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 ends in closing the app.get callback function.

+1
source share

All Articles