I have one function that returns a Promise that needs to call another function that returns a Promise:
getUser(): Promise<User> {
this.getAPIUser().then(result => {
..Do some stuff with result..
return Promise.resolve(result); // This doesn't work
});
}
getAPIUser(): Promise<User> {
return Promise.resolve({ firstName: 'Jason' });
}
I think this doesn't work since the getUser "return Promise.resolve" is in the context of the getAPIUser then handler. This was really easy in Angular 1, you would just instantiate a $q object and then resolve that object wherever you needed it. I can't figure out what the equivalent is in Angular 2/Typescript/EM6.
Any help would be appreciated.
I have one function that returns a Promise that needs to call another function that returns a Promise:
getUser(): Promise<User> {
this.getAPIUser().then(result => {
..Do some stuff with result..
return Promise.resolve(result); // This doesn't work
});
}
getAPIUser(): Promise<User> {
return Promise.resolve({ firstName: 'Jason' });
}
I think this doesn't work since the getUser "return Promise.resolve" is in the context of the getAPIUser then handler. This was really easy in Angular 1, you would just instantiate a $q object and then resolve that object wherever you needed it. I can't figure out what the equivalent is in Angular 2/Typescript/EM6.
Any help would be appreciated.
Share Improve this question edited Aug 23, 2016 at 20:55 Jason asked Aug 23, 2016 at 20:43 JasonJason 2,6174 gold badges43 silver badges48 bronze badges 1- 2 Aren't you just missing a return in getUser() ? – Joe Commented Aug 23, 2016 at 20:46
2 Answers
Reset to default 8Your getUser
method doesn't return a promise at all.
When you invoke the then
method on a promise it returns a Promise
back and that is what your method needs to return:
getUser(): Promise<User> {
return this.getAPIUser().then(result => {
..Do some stuff with result..
return result;
});
}
For the sake of pleteness this works as well:
getUser(): Promise<User> {
return new Promise((resolve) => {
this.getAPIUser().then(user => {
resolve(user);
})
});
}