我正在将 http 请求“封装”为我的 js 代码中的服务。
最初,我的代码有点意大利面条,使用这种方式:
let user;
let business;
// check if the user is authenticated
authenticationService.isAuthenticated().subscribe(authenticated => {
// if is authenticated
if(authenticated) {
// get the user profile data and save it to the user variable
profileService.get().subscribe(data => user = data);
// get the user business data and save it to the business variable
businessService.get().subscribe(data => business = data);
}
});
这很有效,但很糟糕。所以我将整个声明重写为
authenticationService.isAuthenticated()
.pipe(
filter(a => a), // continue only when true
tap(() => {
// as above, get data and save to relative variables
this.profileService.get().subscribe(data => user = data));
this.businessService.get().subscribe(data => business = data));
})
).toPromise();
这更好,但我认为还有更好的方法,只是我不知道。
我错了吗?
最佳答案
你在重构方面已经做得很好了,尽管还有空间使函数更加纯粹,并且只输出结果而不是弄乱变量。还要尝试避免嵌套 subscribe
const getAuthUser=()=>authenticationService.isAuthenticated()
.pipe(
filter(a => a), // continue only when true
switchMap(() =>
zip(this.profileService.get(),
this.businessService.get())
}
).toPromise();
getAuthUser().then(([user,business])=> ......)
关于javascript - 有没有更好的方法来管理嵌套调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58592216/