Javascript 有没有更好的方法来管理嵌套调用?

Javascript 有没有更好的方法来管理嵌套调用?,javascript,rxjs,Javascript,Rxjs,我在js代码中将http请求“封装”为服务 最初,我的代码有点像意大利面条,使用这种方式: let user; let business; // check if the user is authenticated authenticationService.isAuthenticated().subscribe(authenticated => { // if is authenticated if(authenticated) { // get th

我在js代码中将http请求“封装”为服务

最初,我的代码有点像意大利面条,使用这种方式:

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])=> ......)

我认为这个问题更适合于可能的重复,谢谢你在这方面的帮助(做一个更好的程序员)