【发布时间】:2017-10-07 23:15:36
【问题描述】:
我对全局的 NodeJS 和 JS 还是很陌生,在通过 MySQL 查询设置对象属性时遇到了麻烦。
我正在使用 Promise 来避免糟糕的异步效果,但显然我做错了,我的 Agent Obejct 的属性永远不会更新。
代码如下:
class Agent {
constructor(agentId, agentName, agentCountry) {
this.agentId = agentId;
this.agentName = agentName;
this.agentCountry = agentCountry;
}
setAgentCountry () {
var promise = function(agentID) {
return new Promise(function(resolve, reject) {
var query = "SELECT c.CountryID, c.CountryName FROM AgentCountry ac, Country c WHERE ac.AgentID = '" + agentID + "' AND ac.CountryID = c.CountryID";
connection.query(query, function(err, results) {
if (!err) {
resolve(results);
} else {
console.log('Error while performing Query.');
}
});
});
}
promise(this.agentID).then(function(data) {
var string = JSON.stringify(data);
var json = JSON.parse(string);
//the agent property is never updated !!
this.agentCountry = json;
}.bind(this), function(err) {
console.log(err);
});
}
}
我是这样调用方法的:
var agent = new Agent(1,"John Doe", "France");
console.log(agent.agentCountry); //Displays "France"
agent.setAgentCountry();
console.log(agent.agentCountry); //Did not display the table of countries it should
你能帮我解决这个问题吗?
谢谢
【问题讨论】: