这对Angular来说还很陌生,并且在Promises,Observables和async / await中挣扎。
但是,这似乎不起作用。我觉得这与Observables / subscribe的工作方式有关,但我无法解决。
代码段:
initPage() {
fetchCurrentUserDetails().then((user) => { //tasks dependent on current user
//task 1
//task 2
});
}
fetchCurrentUserDetails(): Promise<any> {
return Promise.resolve((async () => {
let currentUser = this.global.getUser();// check if user is defined already
let userId: string = sessionStorage.getItem('userid');
if (currentUser == undefined) {
let initProfile = new Promise(resolve => resolve(this.fetchDetailsFromDB(userId)));
const profile: any = await initProfile; //Waits, but returns before the Observable comes back
let user = new User();
// initialize user with the fetched values
user.id = profile.id; // Undefined, since value not returned yet
user.name = profile.user_name; // Undefined, since value not returned yet
// Set this user in a global variable
this.global.setUser(user);
}
return this.global.getUser();
})());
}
fetchDetailsFromDB(userId: string) {
//callProfileService has nothing but the http.get statement
this.callProfileService(userId).subscribe((response) => {
let profile = response.body.response.data.user;
return profile;
});
}
编辑:添加我对toPromise的尝试:
fetchDetailsFromDB(userId: string) {
this.callUserProfileService(userId).toPromise().then((response) => {
let profile = response.body.response.data.user;
return profile;
});
这是正确的方法吗?如果是这样,如何使等待等待Observable返回?
答案 0 :(得分:2)
实际上,您需要toPromise()
方法,但不要忘记返回这个承诺(回调中的return
是不够的-函数{{ 1}}需要返回一个承诺)。
在其余代码上:像这样使用fetchDetailsFromDB
和Promise.resolve
是一种反模式:作为经验法则,当您已经使用它们时,不要用它们中的任何一个创建新的Promise保证可以使用(例如通过API函数调用)。
下面是使用new Promise
方法的方法:
async
答案 1 :(得分:1)
您可以使用回调
initPage() {
fetchCurrentUserDetails((user) => {
//task 1
//task 2
});
}
fetchCurrentUserDetails(callback) {
const currentUser = this.global.getUser();
if (!currentUser) {
const userId: string = sessionStorage.getItem('userid');
return this.callProfileService(userId).subscribe((response) => {
const profile = response.body.response.data.user;
let user = new User();
user.id = profile.id;
user.name = profile.user_name;
this.global.setUser(user);
return callback(user);
});
} else {
return callback(currentUser);
}
}