James
James

Reputation: 5169

Node.JS MySQL Callback

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?

Upvotes: 0

Views: 2287

Answers (1)

Raynos
Raynos

Reputation: 169511

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

Upvotes: 7

Related Questions