首页 > 解决方案 > 回调不编辑值

问题描述

我尝试从一系列回调中获得结果。问题是根本无法返回任何结果。

这是我想要解决的代码:

主功能 :

let userldap:userLDAP = {controls:[],objectClass:[],dn:"",sn:"",givenName:"",mail:"",uid:"",cn:"",userPassword:""};
let res:ldapRes = {err:"",info:"",user:userldap};

this.ldap.authentication(credentials,res);

所以,基本上,我只是想编辑 res 对象中的值。

服务 :


  public authentication(
    credentials: Credentials,
    res:ldapRes,
  ):void {
    this.ldap.authenticate(credentials.username, credentials.password,function(err:string,user:any,info:string) {
          res.err = err;
          res.info=info;
          res.user=user;
      });
  }

这确实是一个非常基本的用法。尽管如此,身份验证函数中的回调似乎并未编辑 res 对象。

我尝试了很多东西,比如全局上下文或任何东西,但身份验证函数中的回调似乎只是做了他的工作,而不是从宇宙中消失。即使对象被更改,它也只是重置为其旧值。

因此,如果有人知道我在搞砸什么(因为它是代码的基础,定义可变范围的问题,我知道,但找不到解决方案),我会很高兴听到它: ) .

谢谢。

编辑:正如建议的那样,并且已经尝试过,在 auth 函数内的回调中等待并不能解决问题:

public async authentication(credentials : Credentials, res: ldapRes):Promise<ldapRes>{
    //console.log(res);
    await this.ldap.authenticate(credentials.username, credentials.password, function(err:string,user:any,info:string) {
      res.err = err; res.info=info; res.user = user;
      console.log("Callback from inside auth function :");
      console.log(res);
    });
    console.log("Callback from outside auth function :");
    console.log(res);
    return res;
  }

在这种情况下,来自内部的日志就像一个魅力,而外部的日志仍然显示 res 的重置版本(无值)。

标签: typescript

解决方案


我们发现了这样做的方法。问题是我们对 Typescript 中的 Promise 原则的误解。事实上,您可以在函数中返回一个 Promise,而不仅仅是 User 对象。

主功能 :

async verifyCredentials(credentials: Credentials): Promise<User> {
    let proms = new Promise<User>(function(resolve,reject){
      ldap.authentication(credentials).then(val => {
        let foundUser : User = new User();
        foundUser.email = val.user.mail;
        foundUser.firstName = val.user.givenName;
        foundUser.lastName = val.user.sn;
        foundUser.id = val.user.uid;
        resolve(foundUser);
      }) 
    })
    return proms;
  }

LDAP功能:

public async authentication(
    credentials: Credentials,
  ){
    return new Promise<ldapRes>(function(resolve, reject){

      ldap.authenticate(credentials.username, credentials.password,function(err:string,user:any,info:string) {
        resolve({err,user,info});
      });

    });

  }

推荐阅读