0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah it is to be used for your case.
Or, you can just use callbacks ;-)
0

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
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.