0

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!

  • What is "Sequalize"? –  Jan 10 '16 at 18:13
  • Also see http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function. –  Jan 10 '16 at 18:15
  • @torazaburo if you post that link as an answer, I'll mark you as correct. That link answered a question I was also curious about (but didn't ask here) in regards to returning a value from an asynch operation. – Dinosaurs for Friends Jan 10 '16 at 23:32

1 Answers1

0

Okay, I thought of a possible solution immediately after writing the question.

The reason why the console.log(gameState) at the end of the getState function returns null is because it runs asynchronous to the sequelize promises.

In other words, the server took .05 milliseconds to get to the last console.log(gameState), but the server took .15 milliseconds to get to where values are assigned to it.

^ Is that correct?

  • Yes, it is correct. Things that happen in the future do not happen in the present. –  Jan 10 '16 at 18:14