1

I have just started a large project with node.js and I have stumbled upon some callback nightmare issues. I have done some node.js development before, but only small stuff based on tutorials.

I have a user model and a owner model, who is the owner for that user...basically the part I am building in node.js will be a REST service so I need to send a json containing a user and it's owner name. My problem is trying to get the owner name like I would do it in ruby or php and setting it as a property..but it doesn't work.

How do people handle this kind of logic in node.js where you need to change objects in callback functions? Also I do not want it to affect performance.

I am using mysql as the database because this was a requirement. So the code is this:

//find all 
req.models.users.find({
    'id' : req.query.id
}, function(err, users) {
    if (err) console.log(err); //do something better here
    else {
        var json = [];
        users.forEach(function(user) {
            user.getOwner(function(err, owner) {
                user.accountOwner = owner.name;

                json.push(user;
            });    
        });

        res.type('application/json');
        res.send(json);
    }
});

I want to send something like this: [{ 'id': user.id, 'username": user.username, 'email': user.email, 'owner': user.owner.name' }, {...}]

0

1 Answer 1

2

The problem is you are not understanding the control flow of node code. It doesn't go line by line top to bottom in chronological order. So your issue is your res.send(json) happens BEFORE (in time) your user.getOwner callback executes, so you send your empty json, then you stuff things into the json array after it's already been sent. You need to use something like async.each to do your joins, wait for all of the user`s owners to be populated, and then send the response. Or you could actually let the database join the data by writing a SQL join instead of doing N+1 queries against your database.

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

2 Comments

yes I know that I am doing things wrong and that I do not really understand how node.js works,,,I have said this is my first big project in node coming from ruby background...I was looking for a solution and guidance to this fairly easy workflow in node.
I think the problem is you assume since something is easy in ruby/rails, it's easy in node. There is no correlation. Somethings are equally easy in node/ruby, some easy things in ruby are hard in node (like this), and some hard things in ruby are easy in node (like doing that secondary set of DB queries in parallel).

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.