从TypeScript中的回调返回值

问题描述 投票:0回答:2

我在Service.ts文件的typecrypt中有一个功能:

export const doCallAuth = (username, password) => {
    var auth = new Auth({
        url: '...',

      });

      var status;

      auth.authenticate(username, password, function (err, user) {
        if (err) {
          console.log(err);
          status = 'no';

        } else if (!user.uid) {
          console.log("user not found Error");
          status = 'no';
        } else if (user.uid) {
          console.log("success : user " + user.uid + " found ");
          status = 'yes';
        }
      });

      return status;
}

我通过以下方式调用此方法:

var result = Service.doCallAuth('test', 'test');

并且变量结果未定义

我不知道为什么结果未定义

有人可以帮我吗?

谢谢。 :)

javascript node.js typescript callback
2个回答
0
投票

尝试这个。

 auth.authenticate(username, password, function (err, user) {
    if (err) {
      console.log(err);
      status = 'no';
    } else if (!user.uid) {
      console.log("user not found Error");
      status = 'no';
    } else if (user.uid) {
      console.log("success : user " + user.uid + " found ");
      status = 'yes';
    }
    return status
  });

0
投票

用户asyncawait获得值

export const doCallAuth = async function(username, password) => {
    var auth = new Auth({
        url: '...',

      });

      var status;

      auth.authenticate(username, password, function (err, user) {
        if (err) {
          console.log(err);
          status = 'no';

        } else if (!user.uid) {
          console.log("user not found Error");
          status = 'no';
        } else if (user.uid) {
          console.log("success : user " + user.uid + " found ");
          status = 'yes';
        }
      });

      return status;
}

通过以下方式调用此方法:

var result = await  Service.doCallAuth('test', 'test');
© www.soinside.com 2019 - 2024. All rights reserved.