Reputation: 25062
I am trying to learn node
and understand how callbacks are working. I am doing this by trying to use the async
lib. I am trying to hit my db with 2 separate calls and use the async
lib to let me know when my object is ready to build. Here is my aysnc
code:
async.parallel({
one: function(callback) {
getUser(id, callback);
},
two: function(callback) {
getUserServices(id, callback);
}
}, function(err, results) {
if(err) {
console.log(err);
new Error();
}
res.json(result);
});
Here are what my functions look like where I am calling the db. There are both basically the same function:
var getUser = function(id, callback) {
var query = client.query('SELECT * FROM USERS WHERE USER_ID=$1', [id]);
query.on('row', function(row, result) {
result.addRow(row);
});
query.on('end', function(result) {
callback(result);
});
};
My code hits the db
and returns the user
, but when it goes back up to the async
code the user
is in the err
object. What am I doing wrong? How do I properly set up callbacks?
Upvotes: 0
Views: 160
Reputation: 1348
As pointed by damphat, your code should be
//additionally, handle errors
query.on('error', function(err){
callback(err) // The first argument to callback should be an error object
})
query.on('end', function(result){
callback(null, result) //passing null error object
})
Upvotes: 2