javascript - Last callback not being called using async -
i cannot seem last callback (commented "optional callback") called send result browser. pointers doing wrong? using following modules: async, restify , postgresql node.js
console.log('start'); var async = require('async'); var restify = require('restify'); var server = restify.createserver(); server.use(restify.bodyparser()); server.get('/user/creationdate/:username', function(req, res, next) { var username = req.params.username; var record; async.parallel([ function(callback){ getuserbyname(username, function(err, user) { if (err) return callback(err); record = user; }); } ], // optional callback function(err){ console.log('5. following record has been retrieved:' + record); res.send(record); }); next(); }); server.listen(8080, function () { console.log('%s listening @ %s', server.name, server.url); }); handleerror = function handleerror(err) { if(!err) { return false; } else { console.log('the following error occurred:' + err); } return true; }; function getpgclient(){ var pg = require('pg'); var client = new pg.client({ user: 'postgres', password: 'password', database: 'foobar', host: '192.168.1.100', port: 5432 }); client.on('drain', client.end.bind(client)); //disconnect client when queries finished return client; } function getuserbyname(username, callback){ var client = getpgclient(); console.log('2. trying connect db'); client.connect(function(err) { console.log('3. error connecting db:' + handleerror(err)); if(handleerror(err)) return callback(err); client.query("select created_at users username='" + username + "'", function(err, result) { if(handleerror(err)) return; console.log('4. error occurred:' + err); console.log(result); console.log(callback); callback(null, result); }) }); }
i'm not sure why you're using async
since you're calling 1 asynchronous function. reason callback isn't called because you're not ending first function calling callback:
async.parallel([ function(callback) { getuserbyname(username, function(err, user) { // call async callback err , user callback(err, user); }); } ], function(err, record) { console.log('5. following record has been retrieved:' + record); res.send(record); });
or, shorter:
async.parallel([ function(callback) { getuserbyname(callback); } ], function(err, record) { console.log('5. following record has been retrieved:' + record); res.send(record); });
or, in case, shorter (and without need async
):
getuserbyname(function(err, record) { // handle error, or ... console.log('5. following record has been retrieved:' + record); res.send(record); });
Comments
Post a Comment