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

标签 javascript rxjs

我正在将 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/

相关文章:

javascript - 多个 API 请求

javascript - 在可观察订阅上运行函数

javascript - 刷新后过滤器被清除

JavaScript 构造函数 : is this a property or a variable?

javascript - 如何在 Rails 中将 javascript/jQuery 设置从一个页面传递到另一个页面?

typescript - angular2 rxjs 可观察的 forkjoin

javascript - 我如何等待 RxJS 中的所有 Promise 都得到履行?

javascript - 如何避免使用异步服务重复填充数组

javascript - React 子组件可以更改存储在其父组件中的数据吗?

javascript - 如果我路由到另一个组件然后返回,Angular-cli 3rd 方 javascript 将停止工作