jhamm
jhamm

Reputation: 25062

How to wait for result from db in javascript

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?

Upvotes: 0

Views: 170

Answers (2)

npe
npe

Reputation: 15729

Use callbacks, Luke ;-)

You can redefine your functions like this:

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.get(0)); // This one's ugly, but oh well...
  });
}

Then, in your code, use it like this:

var getCompleteUser = function(req, res) {
    getUserService(req.body.id, function(subservices) {
        getUser(req.body.id, function(user) {
            user.subservices = subservices;

            // Go on with your logic here
        }
    }
}

Upvotes: 0

Jayram
Jayram

Reputation: 19588

You could choose any of these options. Either set timeout on next function or use node-async to perform your operation successfully.

Upvotes: 1

Related Questions