gpt4 book ai didi

javascript - 如果从不运行,为什么会这样

转载 作者:行者123 更新时间:2023-12-01 01:08:59 25 4
gpt4 key购买 nike

我想要实现的是:
- 首先回调运行并且
- this.auth.javaAuthToken,它是另一个文件中的属性,被初始化为 token 的值。
- 之后,调用此函数:return this.auth.getUserFiles();

如果我这样做:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<any> {
let token = null;
this.auth.emailListCleaningUserDetail().subscribe((res: any)=>{
token = res.body.data.access_token;
token = this.auth.javaAuthToken;
return this.auth.getUserFiles();
});

然后我收到一个错误:

function must return a value

所以我编写了下面的代码来检查 token 是否存在。如果是这样,那么我调用该函数并返回。

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<any> {
let token = null;
this.auth.UserDetail().subscribe((res: any)=>{
token = res.body.data.access_token;
token = this.auth.javaAuthToken;
console.log(token);
console.log('inside fun');
});
if(token) {
console.log('inside if outside fun');
this.auth.javaAuthToken = token;
return this.auth.getUserFiles();
}
console.log('outside if and fun')
}
}

当我运行该程序时,
- 首先打印 outside if and fun
- 然后打印 token ,并且
- 然后打印inside fun

最佳答案

很简单,当您尝试访问 token 时(当您返回结果时),结果尚不可用。在异步函数中,您必须等待该值或订阅该事件。

如果您订阅了该事件,则只能访问订阅内的值。

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<any> {
let token = null;
this.auth.UserDetail().subscribe((res: any)=>{
token = res.body.data.access_token;
token = this.auth.javaAuthToken;
console.log(token);
console.log('inside fun');

// This is called when you receive your result which can be later as the code below as this is async

});

// token is always null because its declared as null before
// when this code runs, there is no result of your Service yet
if(token) {
console.log('inside if outside fun');
this.auth.javaAuthToken = token;
return this.auth.getUserFiles();
}
console.log('this runs right after the code before but the result is not available yet')
}
}

我想知道这是否也是异步的:

this.auth.getUserFiles();

然后你可以做这样的事情

LoadUserData = async event => {

var token = null;
var userfiles = null;
try {
var response = await this.auth.UserDetail()
if (response.data != null) {
token = response.data.access_token;
console.log('Receiving result: '+JSON.stringify(response.data));
}
} catch (error) {
console.log('ERROR: '+error)
}

try {
var responseUserFiles = await this.auth.getUserFiles();
if (responseUserFiles.data != null) {
// do something with your userfiles
userfiles = responseUserFiles.data;
console.log('Receiving result: '+JSON.stringify(responseUserFiles.data));
}
} catch (error) {
console.log('ERROR: '+error)
}

// Here you can return what you want, userfiles or token
return userfiles;
}

关于javascript - 如果从不运行,为什么会这样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55332389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com