代码之家  ›  专栏  ›  技术社区  ›  Liero

如何重写承诺。所有(promise1.then(),promise2)在角度

  •  0
  • Liero  · 技术社区  · 7 年前

    我有以下代码:

    this.account = await this.backend.getAccountInfo();
    this.personInfo = await this.backend.getPersonInfo(account.userName);
    this.config = await this.backend.getConfig();
    this.loaded = true;
    

    现在我想与account和personInfo并行获取配置,所以我使用promises重写了它:

    var p1 = this.backend.getAccountInfo()
        .then(account => this.account = account, handleError("account"));
    
    var p2 = p1.then(account => this.backend.getPersonInfo(account.userName))
        .then(personInfo => this.personInfo = personInfo, handleError("current person");
    
    var p3 = this.backend.getConfig()
        .then(config => this.config = config, handleError("config");
    
    await Promise.All(p1, p2, p3);
    initialized = true;
    

    假设后端使用HttpClient并返回可观察的结果,我如何使用RxJS重写它?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ingo Bürk    7 年前

    您有三个请求,其中第二个请求取决于第一个请求。第三个是独立的,所以你可以

    Rx.Observable.forkJoin(
      this.backend.getAccountInfo()
        .switchMap(account => this.backend.getPersonInfo(account.userName)
          .map(personInfo => [account, personInfo])
        ),
      this.backend.getConfig()
    )
      .subscribe(([[account, personInfo], config]) => {
        this.account = account;
        this.personInfo = personInfo;
        this.config = config;
    
        this.loaded = true;
      });
    

    但那只是 这样做的方式。例如,这里有另一种使用副作用的方法:

    Rx.Observable.forkJoin(
      this.backend.getAccountInfo()
        .do(account => this.account = account, () => handleError("account"))
        .switchMap(account => this.backend.getPersonInfo(account.userName))
        .do(personInfo => this.personInfo = personInfo, () => handleError("current person"))
      ),
      this.backend.getConfig()
        .do(config => this.config = config, () => handleError("config"))
    )
      .subscribe(() => this.loaded = true);
    

    你应该知道 forkJoin 处理错误并添加 catch 您认为合适的运算符。另请注意,第二个版本将分配 this.account 即使 personInfo 然后请求失败。