如何防止在typescript中调用第一个方法之前调用第二个方法?



我需要在API调用之后调用一个方法。我写了这样的代码

getData(): void {
this.apiCall();
this.processAPIData();
}

processAPIData()方法应该只在apiCall()完成并返回一个成功或true的响应后才被调用。在某些情况下,apiCall()需要更多的时间来返回响应,processAPIData()在apiCall()完成之前被调用。这在功能上几乎没有造成什么问题。我已经尝试使用setTimeout()processAPIData(),但有机会apiCall()可能需要比setTimeout中提到的时间段更长的时间。

由于特殊的要求和条件,我不想把processAPIData()写在apiCall()的主体里面。有没有人能帮我解决这个问题?

编辑:既然有些人问过apiCall()结构,我将添加它的示例结构。

apiCall(): void 
{
this.getAPIData().subscribe((response) => {
this.dataToBeProcessed = response.data;
});
}

你想要实现的是async函数和Promises。

首先,您需要使this.apiCall成为一个async函数。这可以确保它返回一个承诺,你可以等待它。

async apiCall() {
const res = await this.getAPIData().toPromise()
this.dataToBeProcessed = res.data
}

为了能够等待apiCall的结果,您还需要使getDataasync:

async getData() {
await this.apiCall()
this.processAPIData()
}

编辑:使用OP

提供的新信息

可以将getData函数声明为async,并在apiCall中使用await。

async getData() {
await this.apiCall();
this.processAPIData();
}

这是一个js功能。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

最新更新