简体   繁体   English

如何在Angular 2中从另一个Promise函数调用一个Promise函数?

[英]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: 我有一个函数返回一个Promise,而该函数需要调用另一个返回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. 我认为这不起作用,因为getUser“ return Promise.resolve”是在getAPIUser然后处理程序的上下文中。 This was really easy in Angular 1, you would just instantiate a $q object and then resolve that object wherever you needed it. 在Angular 1中,这真的很容易,您只需实例化$ q对象,然后在需要的地方解析该对象。 I can't figure out what the equivalent is in Angular 2/Typescript/EM6. 我不知道什么是Angular 2 / Typescript / EM6中的等效项。

Any help would be appreciated. 任何帮助,将不胜感激。

Your getUser method doesn't return a promise at all. 您的getUser方法根本不返回承诺。
When you invoke the then method on a promise it returns a Promise back and that is what your method needs to return: 当您在promise上调用then方法时,它将返回Promise ,这就是您的方法需要返回的内容:

getUser(): Promise<User> {
    return this.getAPIUser().then(result => {
        ..Do some stuff with result..
        return result;
    });
}

For the sake of completeness this works as well: 为了完整起见,这同样适用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM