Here is a bit of code to demonstrate my issue.
'use strict';
module.exports = function(sequelize, DataTypes) {
var Game = sequelize.define('Game', { ... }, {
tableName: 'games',
instanceMethods: {
getState: function(userClass) {
var currentGame = this;
var gameState = {};
userClass.findOne({ where: { id: currentGame.challenger_user_id }}).then(
function(challengerUser) {
userClass.findOne({ where: { id: currentGame.recipient_user_id }}).then(
function(recipientUser) {
var turn;
if (currentGame.turn_symbol == 'X') {
turn = { user: challengerUser, symbol: 'X' };
} else {
turn = { user: recipientUser, symbol: 'O' };
}
gameState.game = currentGame;
gameState.turn = turn;
gameState.participants = [
{ user: challengerUser, symbol: 'X' },
{ user: recipientUser, symbol: 'O' }
];
console.log(gameState);
// Shows the object with the assigned values
}
);
}
);
console.log(gameState)
// Shows an empty object.
}
},
classMethods: { ... }
});
return Game;
};
In the getState
function, we first declare an empty object named gameState
.
We then find two users -- so we're now nested within two scopes -- and try to assign a value to our gameState
variable.
When doing a console.log within the two nested scopes, the object is shown with all of the assigned values.
gameState
is shown to be an empty object when doing a console.log outside of the two nested scopes (after assigning values).
Can someone help explain my error here?
Also, what is the correct term for these nested scopes -- are they promises?
Thanks!