Huy Vũ
Huy Vũ

Reputation: 45

Scope JavaScript

I am new to JavaScript. In the code below, when I log in, I try to get the user info from database and store in user object. However, when I check the user in the commandManager scope, it turns null. How can I make user not null?

Here is the code:

function LogInCommand(username, password) {
  return new Command(function (user) {
    api
      .logIn(username, password)
      .then(function (data) {
        user = data;
        console.log(user);
      })
      .catch(function (error) {
        console.log(error);
      });
  });
}

function createCommandManager() {
  var user = null;

  return {
    execute: function (command, ...args) {
      command.execute(user, ...args);
    },
    user: user
  };
}

var commandManager = createCommandManager();

commandManager.execute(new LogInCommand("[email protected]", "123456"));
setTimeout(function() {
  console.log(commandManager.user);
}, 10000);

Here is the result:

{age: 21, connection: null, email: "[email protected]", name: "andy", pendingConnection: null, …}
null

Thanks all of you for your helps!

Upvotes: 0

Views: 46

Answers (2)

Jeremiah Taberna
Jeremiah Taberna

Reputation: 11

One the things that are ovious in the code are that there not closed in the correct wy and that there are command that are missing.

Upvotes: -1

Since you change your user variable directly. It will break reference and it will not work. If you want to do it with your way. You can change your code like the below.

function LogInCommand(username, password) {
  return new Command(function (initialData) {
    api
      .logIn(username, password)
      .then(function (data) {
        initialData.user = data;
        console.log(initialData.user);
      })
      .catch(function (error) {
        console.log(error);
      });
  });
}

function createCommandManager() {
  var initialData = {
     user: null,
  };

  return {
    execute: function (command, ...args) {
      command.execute(initialData, ...args);
    },
    data: initialData
  };
}

commandManager.execute(new LogInCommand("[email protected]", "123456"));
setTimeout(function() {
  console.log(commandManager.data.user);
}, 10000);

Upvotes: 2

Related Questions