如果第一个Promise出错,我该如何返回另一个Promise?

问题描述 投票:0回答:1

具体情况是:

  • 我正在使用本地存储API,当您尝试“获取”该值时,它会返回一个承诺。我想要获得的值是一个自定义的“UserProfile”对象。
  • 如果该值未定义或为null,那么我想进行http调用以使用Web请求获取UserProfile

也许我只是不太了解Promise。

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

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'

angular angular-promise
1个回答
1
投票

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

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

或者在awaitasync方式:

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然后:

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

更整洁:)

最后,为了解释为什么你的方法不起作用,是因为你没有在then中返回用户时它不是null,如果你不想那么“彻底”改变你的代码,你也可以这样做:

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();
    }
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.