0

I'm using the 'user-management' package in Node, and I have a callback within a callback, within a callback. But the final result doesn't return. This is my main NodeJS module:

 playerManagement.login(data.username, data.pw, function (result) {

      console.log(result) <-- statement never reached

      if (result == "fail") {
        socket.emit('client', { type: 'login', result : 'fail'});
      } else {
        connections[playerindex++] = {'username' : username, 'sockid' : socket.id, 'token' : result };
        socket.emit('client', { type: 'login', result : 'success', username : username });
        console.log(connections);
      }

  });

Then I have an external module with the function:

playerModule.prototype.login = function(username, password) {

var o = this;

o.user.load(function (err) {
    if (!err) {
        o.user.authenticateUser(username, password, function(err, result) {

            if (!result.userExists) {
              console.log('Invalid username');
              return "fail";
            } else if (!result.passwordsMatch) {
              console.log('Invalid password');
              return "fail";
            } else {
              console.log('User token is: ' + result.token); <--- this is reached.
              return result.token;
            }
        });
    } else {
        console.log('error logging in');
        return "fail";
    }
});

So I'm guessing I need to return the value to the "load" function callback, but I'm not sure how to do that.

The Hawk
  • 1,496
  • 6
  • 26
  • 43

1 Answers1

2

Change the definition of login with the following.

playerModule.prototype.login = function(username, password, callback)  {

  var o = this;

  o.user.load(function (err) {
  if (!err) {
    o.user.authenticateUser(username, password, function(err, result) {

        if (!result.userExists) {
          console.log('Invalid username');
          return callback("fail");
        } else if (!result.passwordsMatch) {
          console.log('Invalid password');
          return callback("fail");
        } else {
          console.log('User token is: ' + result.token); <--- this is reached.
          return callback(result.token);
        }
    });
  } else {
    console.log('error logging in');
    return callback("fail");
  }
});
Mukesh Sharma
  • 8,914
  • 8
  • 38
  • 55