所以,一旦我解决了我之前的问题的承诺问题,我尝试在登录时从数据库中获取玩家帐户 X、Y 坐标(这样它们就不会放在 1,1 上,而是放在他们最后跟踪的坐标上)
经过一番调试,我得出了这个结论:
var x; //note I also tried to define these directly above the getX/Y() and it didn't work
var y;
return con.getConnectionAsync().then(function(connection) {
return connection.queryAsync('SELECT password,id FROM player WHERE name='+mysql.escape(req.body.user))
.spread(function(rows, fields) {
if (hash.verify(req.body.pass,rows[0].password)) {
req.session.loggedIn = true;
req.session.user = rows[0].id;
getX(rows[0].id,con,mysql).then(function(data) {
x = data;
});
getY(rows[0].id,con,mysql).then(function(data) {
y = data;
});
console.log(x,y,"line77");
ref = new P(rows[0].id,x,y);
res.send({
"msg":"You have logged in!",
"flag":false,
"title":": Logged In"
});
return ref;
} else {
res.send({
"msg":"Your username and or password was incorrect.",
"flag":true,
"title":": Login Failed"
});
}
}).finally(function() {
connection.release();
});
});
这就是整个功能——以防万一缺少某些范围。但这里是麻烦线:
getX(rows[0].id,con,mysql).then(function(data) {
x = data; //x logs the return 7 from the db
});
getY(rows[0].id,con,mysql).then(function(data) {
y = data; //y logs 45 from the db
});
console.log(x,y,"line77"); //logs "undefined undefined line77"
ref = new P(rows[0].id,x,y);
我的印象Promise
是会在我的查询完成之前解决这个函数触发问题,但我想不会。
为什么我的函数在设置 X、Y 变量之前返回?
注意:下一步是将我的关注点与函数分开,所以请忽略我在传递con
,mysql
就像在比赛中的接力棒一样。谢谢!