我有一个嵌套函数,可以在短暂的延迟后进行API查询。嵌套函数在for循环中调用,该循环调用该嵌套函数90次。我需要弄清楚如果API响应中有错误,如何防止循环触发90次。
我尝试添加变量this.didTaskFail来检查API响应是否返回错误。我的想法是,我可以在for循环中添加条件,以检查didTaskFail是否返回true,然后退出for循环。但是问题是API响应的异步性质。 for循环几乎立即发生,然后90错误响应开始进入我的终端。
private _pollForRankingTaskCompletion(rankingTaskId, callback) {
let retry = (delay: number, is_first: boolean = false, is_last: boolean = false) => {
if (is_first) {
this.isRankingPollComplete = false
}
_.delay(() => {
if (!this.isRankingPollComplete) {
this._apiService.fetch(`tasks/${rankingTaskId}`).subscribe(
(response: any) => {
if (response.success) {
this.isRankingPollComplete = true;
if (callback) callback(response);
this._app.showMessage(`Your activities are synced and rankings finished updating.`, null, AppService.UIMessageStyle.Success);
this._app.broadcast(AppEvents.RANKINGS_UPDATED)
} else if (is_last && !this.isRankingPollComplete) {
this._app.showMessage(`Due to high traffic volume this will take longer than
normal. Please check back later, we apologize for the inconvenience.`, null, AppService.UIMessageStyle.Warning);
// reset vars
this.isSyncing = false;
this._app.didJustSignUp = false;
this.isFirstTimeAutoSyncing = false;
}
},
(error: any) => {
this.didTaskFail = true
console.error(error)
}
)
}
}, delay)
};
const numRetries = 90;
for (let i = 0; i <= numRetries; i++) {
console.log("didTaskFail?:", this.didTaskFail)
if (i == 0) {
retry(1000, true);
} else {
retry(i * 1500, false, i === numRetries)
}
}
}
我不确定在没有完全重新设计_pollForRankingTaskCompletion的情况下是否存在一种干净的方法。但是,作为一个停顿点,我希望能够打破循环并向用户输出一条错误消息,而不必经历循环并向用户显示90条错误消息。到目前为止,我尝试过的所有可能解决方案都会输出90条错误消息