【问题标题】:JavaScript/NodeJS Callback within a callback [duplicate]回调中的 JavaScript/NodeJS 回调 [重复]
【发布时间】:2017-04-10 02:55:55
【问题描述】:

我在 Node 中使用“用户管理”包,并且在回调中,在回调中,我有一个回调。但最终结果不会返回。这是我的主要 NodeJS 模块:

 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);
      }

  });

然后我有一个具有该功能的外部模块:

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";
    }
});

所以我猜我需要将值返回给“加载”函数回调,但我不知道该怎么做。

【问题讨论】:

  • 你应该使用承诺。
  • 如果要接受回调,实际上需要有回调参数,并调用它。
  • 因为你的login函数定义没有回调作为参数,
  • 您无法返回异步结果。您的函数在获得异步结果之前很久就返回了。相反,您必须使用承诺或回调来传达最终结果。

标签: javascript node.js callback user-management


【解决方案1】:

使用以下内容更改login 的定义。

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");
  }
});

【讨论】:

    猜你喜欢
    • 2016-11-15
    • 2013-10-07
    • 1970-01-01
    • 2020-10-04
    • 2017-09-03
    • 2014-03-15
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多