Node.JS MySQL回调

Jam*_*mes 0 mysql asynchronous callback node.js

由于Node是异步的,我在尝试获取回调以正确返回值时遇到问题.

我尝试过以下方法:

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);
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

但是,显然由于竞争条件,userName变量永远不会被回调设置this.tableLookup.

那么我怎样才能得到这个价值呢?

Ray*_*nos 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;
Run Code Online (Sandbox Code Playgroud)

所以修复你的代码

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);
        });
    }
},
Run Code Online (Sandbox Code Playgroud)

并使用

libUser.getName(name, function (user) {
  // do something
});
Run Code Online (Sandbox Code Playgroud)