Jason Jason - 3 months ago 11
TypeScript Question

How to call one Promise function from another Promise function in Angular 2?

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.

Answer

Your 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;
    });
}
Comments