I am using node with the pg module to talk with Postgres. I am trying to abstract out a few functions so I can reuse them, but node's non-blocking has me messed up.
I have create 2 functions, one to get the user:
var getUser = function(id) {
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) {
return result;
});
}
And then another function to get services that are attached to the user:
var getUserServices = function(id) {
var query = client.query('SELECT * FROM SERVICES WHERE USER_ID = $1', [id]);
query.on('row', function(row, result) {
result.addRow(row);
});
query.on('end', function(result) {
var services = _.map(result.rows, function(row) {
return row.subservice_id;
});
return services;
});
}
I then call the functions in another method like this:
var getCompleteUser = function(req, res) {
var user = getUser(req.body.id);
var subservices = getUserService(req.body.id);
user.subservices = subservices;
};
But when I try to attach the services to the user, the user is not created yet. I am sure this is a complete noob question, but I cannot figure this out. What do I do?