gpt4 book ai didi

javascript - 与状态相关的每 5 秒运行一次方法

转载 作者:行者123 更新时间:2023-12-04 12:04:11 25 4
gpt4 key购买 nike

我在组件中有从后端获取数据并检查状态的方法
就这个

 getRecognitionById() {
this.loaderService.show(null, true);

this.vendorWebApiService
.createRecognition(this.executiveChangeId)
.pipe(take(1))
.subscribe((res) => {
this.vendorWebApiService
.getRecognition(res.taskRequestId, this.executiveChangeId)
.pipe(take(1))
.subscribe((recognitionResponse) => {
if (recognitionResponse.jobStatus === "completed") {
this.recognitionData = recognitionResponse;
this.getLatesFeedback();
}
if (recognitionResponse.jobStatus === "failed") {
alert();
} else {

}
});
});
}
在这部分我检查状态
 this.vendorWebApiService
.getRecognition(res.taskRequestId, this.executiveChangeId)
.pipe(take(1))
.subscribe((recognitionResponse) => {
if (recognitionResponse.jobStatus === "completed") {
this.recognitionData = recognitionResponse;
this.getLatesFeedback();
}
if (recognitionResponse.jobStatus === "failed") {
alert();
} else {

}
});
但是如果状态是另一个然后完成或失败的问题,我需要每 5 秒重新运行一次这个逻辑,所以每 5 秒我需要检查一次状态,并且在 10 次尝试后,我需要显示警报。
我需要如何重写我的代码来实现这个逻辑?

最佳答案

你可以用 rxjs 做到这一点

    import { interval, Subject, Subscription } from 'rxjs';
refresher$: Observable<number>;
refreshSub: Subscription;
jobStatus: string = "init"
checkCount = 0

checkStatus() {
this.checkCount++
this.vendorWebApiService
.getRecognition(res.taskRequestId, this.executiveChangeId)
.pipe(take(1))
.subscribe((recognitionResponse) => {
jobStatus = recognitionResponse.jobStatus
this.recognitionData = recognitionResponse

});
}

getRecognitionById() {
this.loaderService.show(null, true);

this.checkStatus()
}

this.refresher$ = interval(5000); // every5 sec
this.refreshSub = this.refresher$.subscribe(() => {
this.checkStatus()
if (this.jobStatus === 'completed') {
this.getLatesFeedback();
}
if (this.jobStatus === 'failed') {
alert()
} else {
if (this.checkCount == 10) {
alert()
}
}

});

关于javascript - 与状态相关的每 5 秒运行一次方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69536836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com