简体   繁体   English

如何使用连锁电话Promise?

[英]How to use chain calls Promise?

Now in .then section I all another promise http request: 现在在.then部分,我所有其他的诺言http请求:

.then(result => { this.service().then(data => {}); });

Is it a correct way to use chained promises? 使用链式诺言是正确的方法吗?

Almost! 几乎! You need to return the promise in the function, either like this: 您需要在函数中返回promise,如下所示:

.then(result => { return this.service().then(data => {}); });

or like this: 或像这样:

.then(result => this.service().then(data => {}));

Since you are using Typescript, you could use async/await to chain promises in a more readable way: 由于您使用的是Typescript,因此可以使用async/await以更加可读的方式链接promise:

function firstCall(): Promise<any> { /* return a promise */ }
function service(): Promise<any>{ /* return a promise */ }

async function runPromisses() {
    var result = await firstCall();
    var data = await service();
    // ...
}

Yes, your two promises are resolved sequentially. 是的,您的两个承诺会按顺序解决。 But remember that your second (the inner) promise will only be called when the first then was successfully resolved. 但是请记住,您的第二个(内部)承诺仅在第一个然后成功解决后才会被调用。

An even cleaner solution would be: 甚至更清洁的解决方案是:

.then(result => this.service()).then(data => {});

As elaborated in this SO answer by Hrishi, returning a "thenable" (for example a Promise) inside your then() function, makes the old promise adopt the state of the new promise. 正如Hrishi在此SO答复中所详细说明的那样,在then()函数内部返回“ thenable”(例如Promise),使旧的Promise采纳新Promise的状态。

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

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