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