typescript - 回调不编辑值
问题描述
我尝试从一系列回调中获得结果。问题是根本无法返回任何结果。
这是我想要解决的代码:
主功能 :
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 中的 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});
});
});
}
推荐阅读
- javascript - 如何复制 javascript 生成的链接的网址?
- reactjs - 反应路由器渲染与组件给我错误
- jwt - 何时是使用 JWT 注销用户的正确时间,访问令牌到期的时间或刷新令牌的到期时间?
- laravel - 如果条件与 Laravel 中的数组
- vba - 什么是删除访问表单附件控件上的附件的编程方法?
- android - Glide 4.9.0 无法使用 MyAppGlideModule 加载 firebase 图片
- html - 将输入类型=“文本”仅限制为数字并在反应 js 的输入框中显示默认的前 3 个数字
- flutter - Gridview没有在风景中填充身体
- android - RecyclerView:没有附加适配器;在片段中跳过布局
- php - Codeigniter 会话在每个请求中刷新