代码之家  ›  专栏  ›  技术社区  ›  Ambrose Leung

如果第一个承诺出现错误,我如何返回不同的承诺?

  •  0
  • Ambrose Leung  · 技术社区  · 7 年前

    具体情况是:

    • 如果该值未定义或为null,那么我想使用web请求进行http调用以获取UserProfile

    下面是我想做的非工作代码,但我不知道语法是如何工作的。

    getUserProfile() {
      return this.storage.get("userProfile")
        .then(user => {
          if (user == null) {
            throw new Error("no user profile");
          }
        }
        )
        .catch(error => {
          //I don't know how to return a different promise
          return this.getUserProfileWithHttpCall();
        }
      );
    }
    
    //I want to return this in getUserProfile() if "userProfile" doesn't exist in "storage"
    getUserProfileWithHttpCall(): Promise < UserProfile > {
      return this.http.get(this.baseUrl + "/Account/GetUserInfo")
        .toPromise()
        .then(
        response => {
          this.storage.set("userProfile", response);
          return response;
        }
      );
    }
    

    this.storage 是来自“@ionic/Storage”的存储

    this.http 是HttpClient'@angular/common/http'

    1 回复  |  直到 7 年前
        1
  •  1
  •   Poul Kruijt    7 年前

    对于你的想法,没有必要抛出任何错误。您可以这样做:

    getUserProfile() {
      return this.storage.get("userProfile")
        .then(user => user || this.getUserProfileWithHttpCall()
      );
    }
    

    或者在 await async 方式:

    async getUserProfile() {
      return (await this.storage.get("userProfile")) || this.getUserProfileWithHttpCall();
    }
    

    也许你想用 Observables ,因为他们现在很时髦。您可以将其更改为:

    getUserProfile() {
      return from(this.storage.get("userProfile")).pipe(
        concatMap((user) => user ? of(user) : this.getUserProfileWithHttpCall())
      );
    }
    

    getUserProfileWithHttpCall(): Observable<UserProfile> {
      return this.http.get(`${this.baseUrl}/Account/GetUserInfo`).pipe(
        tap((user:UserProfile) => this.storage.set("userProfile", user))
      )
    }
    

    最后,要解释为什么您的方法不起作用,是因为您没有在 then

    getUserProfile() {
      return this.storage.get("userProfile")
        .then(user => {
          if (user == null) {
            throw new Error("no user profile");
          }
    
          return user; // you missed this one
        }
        )
        .catch(error => {
          //I don't know how to return a different promise
          // Like you already did
          return this.getUserProfileWithHttpCall();
        }
      );
    }