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
設置。
那麼我怎樣才能得到這個值呢?
玉不理解異步> :( – Raynos 2012-01-17 14:17:55
提示:這是因爲競爭條件,你的異步不行不行。 .. – jcolebrand 2012-01-17 15:24:27
謝謝,這對我來說是有意義的,現在Raynos已經展示了回調如何在節點中工作:)如果它是jQuery中的AJAX請求,但是在這個ca中沒有'async'切換,我可以解決這個問題SE。 – James 2012-01-17 15:58:49