2012-01-17 85 views
0

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

我已经试过如下:

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

然而,由于明显的竞争条件,在userName变量从未通过回调从this.tableLookup设置。

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

+4

玉不理解异步> :( – Raynos 2012-01-17 14:17:55

+1

提示:这是因为竞争条件,你的异步不行不行。 .. – jcolebrand 2012-01-17 15:24:27

+0

谢谢,这对我来说是有意义的,现在Raynos已经展示了回调如何在节点中工作:)如果它是jQuery中的AJAX请求,但是在这个ca中没有'async'切换,我可以解决这个问题SE。 – James 2012-01-17 15:58:49

回答

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; 

所以解决您的代码

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

,并使用

libUser.getName(name, function (user) { 
    // do something 
}); 
+0

简单来说,整个sytanx /回调的概念,很好的解释,它甚至在2017年有用:) – Fahad 2017-02-17 14:10:09