[英]Node.JS MySQL Callback
由于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);
});
}
};
但是,显然由于竞争条件, userName
变量永远不会由this.tableLookup
的回调设置。
那么,如何才能收回该价值?
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.