Reputation: 4984
I have a Typescript method like this and I would like that it returns a Promise, but only after the this.user.currentCourseId = student.currentCourseId;
line is executed.
Is it possible?
public getUserData()
{
...
this.authState.auth.getToken().then(token =>
{
this.user.token = token;
this.userService.update(this.user).then(student =>
{
this.user.currentCourseId = student.currentCourseId;
});
});
}
Upvotes: 2
Views: 1397
Reputation: 101758
As jfriend points out, you can't wait to return a promise until after it has finished. That would be putting the cart before the horse. You return the promise right away, and chain off of it to wait on its completion.
I just want to point out that you should take advantage of promise chaining to avoid the habit of sliding toward the "tower of doom":
public getUserData()
{
...
// return promise from function
return this.authState.auth.getToken().then(token =>
{
this.user.token = token;
// return promise here to chain to original promise
return this.userService.update(this.user)
}).then(student => {
this.user.currentCourseId = student.currentCourseId;
});;
}
getUserDate().then(() => {
// currentCourseId has been set now
});
Upvotes: 1
Reputation: 708036
You return the promise immediately. And, any other promises inside the first .then()
handler get returned inside of that so that they are chained to the original promise:
public getUserData()
{
...
// return promise from function
return this.authState.auth.getToken().then(token =>
{
this.user.token = token;
// return promise here to chain to original promise
return this.userService.update(this.user).then(student =>
{
this.user.currentCourseId = student.currentCourseId;
});
});
}
// usage
getUserDate().then(() => {
// values are set here
});
Upvotes: 1