最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to call one Promise function from another Promise function in Angular 2? - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

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

For the sake of pleteness this works as well:

getUser(): Promise<User> {
    return new Promise((resolve) => {
        this.getAPIUser().then(user => {
            resolve(user);
        })
    });
}
发布评论

评论列表(0)

  1. 暂无评论