So, once I sorted out my promise issues with my previous problems, I tried to grab the Player accounts X,Y coordinates from the database upon login (so that they are not placed on 1,1, but instead on their last tracked coordinates)
After some debugging, I came to this:
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();
});
});
That's the whole function -- just in case some scope is missing. But here is the trouble lines:
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);
I was under the impression Promise
would solve this issue of functions triggering before my query is complete, but I guess not.
Why is my function returning before the X,Y variables are set?
Note: the NEXT step is to separate my concerns from the functions, so please ignore that I am passing around con
and mysql
like a baton at a race. Thanks!