node.js: Asynchronous Callback Values

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?

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

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.