2012-01-17 156 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