gpt4 book ai didi

javascript - 复杂 else if 梯子的替代方案

转载 作者:行者123 更新时间:2023-11-28 14:09:39 24 4
gpt4 key购买 nike

我有一个返回名为 user_id 的值的函数。但有很多条件需要检查。

条件1:检查服务变量

条件2:如果否,从localstorage获取user_id

条件3:如果否,从本地存储获取firebase_uid,并调用函数findUserId(firebase_uid),该函数将返回user_id

条件 4:如果否,从 firebase 获取 uid 并调用 findUserId(uid)

这是代码。

export class UserService {

user_id : any;
firebase_uid: any;
id: any;

returnUser_id() {

if(this.user_id) {

return this.user_id
}

else {
this.storageService.get('user_id').then(val =>{
if(val) {
this.user_id =val
return this.user_id
}

else {
this.storageService.get('firebase_uid').then(value =>{
if(value) {
this.firebase_uid = value

this.findUserId(this.firebase_uid).subscribe(q =>{
console.log(q)
this.id = q;
for(let i =0; i<this.id.length;i++) {
this.user_id = this.id[i].id

return this.user_id

}


this.storageService.set('user_id', this.user_id ).then(result => {
console.log('Data is saved');
}).catch(e => {
console.log("error: " + e);
});


})

}
else {
this.afauth.authState.subscribe(user =>{
if(user) {
this.firebase_uid = user.uid;


this.storageService.set('firebase_uid', this.firebase_uid ).then(result => {
console.log('Data is saved');
}).catch(e => {
console.log("error: " + e);
});


this.findUserId(this.firebase_uid).subscribe(data =>{
this.id = data;

for(let i = 0 ;i<this.id.length; i++ ){
this.user_id = this.id[i].id
return this.user_id
}

this.storageService.set('user_id', this.user_id ).then(result => {
console.log('Data is saved');
}).catch(e => {
console.log("error: " + e);
});
})
}
})
}


}).catch(err =>{
console.log(err)
})
}
}).catch(err =>{
console.log(err)
})
}

}

}

findUserId函数

findUserId(uid): Observable<any> {
return this.http.get<User[]>(this.user_url + 'users?filter[fields][id]=true&filter[where][firebase_uid]=' +uid )

}

这段代码非常复杂,难以理解。是否有传统 if else 语句的替代方案。

提前谢谢

最佳答案

有一些可重复的代码,因此我们可以将可重复的代码移至方法中并重用它。此外,我们可以简化我们的代码using async keywords .

if(this.user_id)   
return this.user_id;
else {
let user_id = await this.storageService.get('user_id');
if (user_id)
return user_id;
else {
let firebase_uid = await this.storageService.get('firebase_uid');
if (firebase_uid) {
await reusableFindUserId(firebase_uid);

if (this.user_id)
await setStorageService();
}
else {
let user = await this.afauth.authState();
if (user) {
this.firebase_uid = user.uid;
await reusableFindUserId(firebase_uid);

if (this.user_id)
await setStorageService();
}
})
}
}
}

和可重用的方法:

async reusableFindUserId(firebase_uid){
this.id = await this.findUserId(firebase_uid);
for(let i =0; i<this.id.length;i++) {
this.user_id = this.id[i].id;
return this.user_id;
}
}

async setStorageService() {
return await this.storageService.set('user_id', this.user_id );
}

关于javascript - 复杂 else if 梯子的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60052003/

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