具体情况是:
也许我只是不太了解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'
对于你的想法,没有必要抛出任何错误。你可以这样做:
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然后:
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();
}
);
}