繁体   English   中英

如何强制一段代码等到 Typescript 中的 API 调用完成?

[英]How can I force one block of code to wait until an API call finishes in Typescript?

我正在进行 API 调用,并希望调用后的代码在 API 调用完成之前不运行。

我有一个 function this.api_call ,它调用一个 API 并在 API 调用完成后返回一个数组returnValue

let returnValue = this.api_call(data);

//This line should not run until returnValue has been set
this.otherFunction(returnValue[0], returnValue[1]);

我怎样才能让那一行在运行前等待? 我希望其他代码在 API 调用完成之前仍然能够运行,这只是应该等待的一行。

that's where Promises come in, If your function this.api_call(data) returns a Promise, you can then call the then function on it, with a callback, and this callback will be run only after the promise has resolve.

this.api_call(data).then((returnValue) => {
    this.otherFunction(returnValue[0], returnValue[1]);
});

您还可以使用RxJS 的 observable ,它允许您在使用pipe function 恢复数据之前更改数据。 如果您使用的是 observable,请确保您subscribe了您的 observable,否则它将永远不会被解雇。
如果您的this.api_call(data) function 返回一个可观察对象(通常是使用 Angular 的情况),请像这样使用它:

this.api_call(data).subscribe((returnValue) => {
    this.otherFunction(returnValue[0], returnValue[1]);
});

还有一种方法可以使用async / await关键字,但我不是这个概念的专家,所以我会让其他人回答这个问题。

有多种实现方式,最简单的一种是 Promise 的 async / await 语法:

async function myAsyncFunction(): Promise<void> {
    let returnValue = await this.api_call(data);

    this.otherFunction(returnValue[0], returnValue[1]);
}

this.api_call(data)在您的示例中必须返回一个Promise<ArrayLike<...>>

暂无
暂无

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

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