0

Since Node is asynchronous, I'm having problems trying to get a callback to return values to me properly.

I've tried the following:

var libUser = {
    lookupUser: {},
    getName: function(userID) {
        // If it's in our cache, just return it, else find it, then cache it.
        if('userName_' + userID in this.lookupUser) {
            return this.lookupUser['userName_' + userID];
        }else{
            // Lookup the table
            var userName;
            this.tableLookup(["agent_name"], "_login_", " WHERE agent_id = " + userID, function(d) {
                userName = d[0].agent_name;
            });

            this.lookupUser['userName_' + userID] = userName; // Add to cache

            return userName;
        }
    },
    tableLookup: function(fields, table, clauses, cb) {
        var query = "SELECT " + fields.join(", ") + " FROM " + table + " " + clauses;
        client.query(query, function(err, results) {
            if(err) console.log(err.error);

            cb(results);
        });
    }
};

However, obviously due to race conditions, the userName variable is never set by the callback from this.tableLookup.

So how can I get this value back?

3
  • 4
    y u no understand asynchronous >:( Commented Jan 17, 2012 at 14:17
  • 1
    hint: it's not because of race conditions that your asynchronous doesn't work ... Commented Jan 17, 2012 at 15:24
  • Thanks, it makes sense to me now Raynos has shown how callbacks can work in node :) I can solve the problem if it's an AJAX request in say jQuery, but there is no async toggle in this case. Commented Jan 17, 2012 at 15:58

1 Answer 1

7
 var userName; // user name is undefined
 this.tableLookup(["agent_name"], "_login_", " WHERE agent_id = " + userID, function(d) {
     // this will run later
     userName = d[0].agent_name;
 });

 // username still undefined
 return userName;

So fix your code

getName: function(userID, cb) {
    var that = this;
    // If it's in our cache, just return it, else find it, then cache it.
    if ('userName_' + userID in this.lookupUser) {
        cb(this.lookupUser['userName_' + userID]);
    } else {
        // Lookup the table
        var userName;
        this.tableLookup(["agent_name"], "_login_", " WHERE agent_id = " + userID, function(d) {
            userName = d[0].agent_name;

            that.lookupUser['userName_' + userID] = userName; // Add to cache
            cb(userName);
        });
    }
},

and use

libUser.getName(name, function (user) {
  // do something
});
Sign up to request clarification or add additional context in comments.

1 Comment

The entire sytanx/concept of callback in a nutshell , well explained , its even useful in 2017 :)

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.