1

I'm pretty confused. I would love to learn how I can pass the values I get in an async function on.

I have a module with basic auth functions. In the login I ask the User model to search for a user with a given username.

login: function(req){
    var username = req.body.username,
        password = req.body.password;

    user.find(username);
}

Then the User model goes on and does that.

exports.find = function(username){
console.log(User.find({username: username}, function(error, users){
    // I get nice results here. But how can I pass them back.
}));
}

But how can I pass that user object back to the login function?

2
  • 1
    Your example code is confusing. I think what you are missing is a callback function in the exports.find function. But if you call this from the login function you would create infinite recursion... maybe you mixed that up in your question? Commented Feb 18, 2013 at 18:09
  • After fighting with this simple problem for so long I'm confused. One up for the solution. Commented Feb 18, 2013 at 19:58

2 Answers 2

2

You need to pass a callback function to the method. Node.js requires a very callback-driven programming style.

For example:

// in your module
exports.find = function(username, callback){
    User.find({username: username}, function(error, users){
        callback(error, users);
    });
}

// elsewhere... assume you've required the module above as module
module.find(req.params.username, function(err, username) {
    console.log(username);
});

So you don't return values; you pass in functions that then receive the value (rinse, repeat)

Your login method on the User class would then look something like this:

login: function(req, callback){
    var username = req.body.username,
        password = req.body.password;

    user.find(username, function(err, user) {
        // do something to check the password and log the user in
        var success = true; // just as an example to demonstrate the next line
        callback(success); // the request continues
    };
}
Sign up to request clarification or add additional context in comments.

4 Comments

Although most of this answer is on track, the comparison to "procedural" is not relevant. The synchronous/asynchronous distinction has nothing really to do with whether the code is procedural, functional, or of some other type.
You're right; I changed it to callback-driven. In my defence it's 5am in Sydney :) Wanted to make the point you have to think differently, using callbacks instead of returning values.
Ok, we'll let this one pass. Had it been 6AM, though... :-)
Passing a callback into user.find() was the solution. So simple, yet so essential. Thank you. Good lesson.
0

You can't pass it back (because the function os asynchronous and login would already have returned when it's done). But you can pass it ahead to another function.

Comments