gpt4 book ai didi

javascript - setInterval 永远不会在函数中触发,并且不知道为什么( Angular )

转载 作者:行者123 更新时间:2023-12-03 03:59:07 26 4
gpt4 key购买 nike

我有这个函数,由于某种原因,它直接从打印“在 jobstart 调用后提交组件行”到“进入 while 循环”:

returned() {
this.numReturned++;
if (this.numReturned !== this.numSubmitting) {
return;
}
console.log('submit component line before jobstart call');
this.submitService.startJobToAuditTable().subscribe();
console.log('submit component line after jobstart call');

let timer = setInterval(() => {
console.log('start of interval');
this.submitService.checkIfJobRunning().subscribe(res => {
console.log("res from job running check is " + res);
this.jobFinished = res;
});

this.submitService.pollAuditTable().subscribe(res => {
console.log("res from audit table:\n\t" + res);
this.auditRows = res;
});
}, 10000); //runs every 10 seconds. will be longer after testing

console.log('entering while loop');
while (this.jobFinished === false) {

}

console.log('clearing interval, job should be finished now');
clearInterval(timer);
return;
}

console.log 和 setInterval 内的其他内容永远不会被调用,我很困惑为什么会这样

最佳答案

您的 while 循环正在消耗执行并阻塞一切。如果您想等到作业完成而不是 while(done){} 循环,您可以返回一个 promise :

returned() {
return new Promise((resolve, reject) => {
this.numReturned++;
if (this.numReturned !== this.numSubmitting) {
resolve();
return;
}
console.log('submit component line before jobstart call');
this.submitService.startJobToAuditTable().subscribe();
console.log('submit component line after jobstart call');

let timer = setInterval(() => {

console.log('start of interval');
this.submitService.checkIfJobRunning().subscribe(res => {
console.log("res from job running check is " + res);
this.jobFinished = res;
});

this.submitService.pollAuditTable().subscribe(res => {
console.log("res from audit table:\n\t" + res);
this.auditRows = res;
});

--> if(this.jobFinished === false) {
console.log('clearing interval, job should be finished now');
clearInterval(timer);
resolve();
}

}, 10000); //runs every 10 seconds. will be longer after testing

}
}
在异步代码中,使用

resolve() 代替 return

稍后,当您调用此函数时,如果您想等到作业完成,可以使用 await 关键字

await returned ();  // will wait until resolve() is called
// code after all jobs done

或者如果异步/等待不是首选:

returned().then(() => {
// code after all jobs done
})

关于javascript - setInterval 永远不会在函数中触发,并且不知道为什么( Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44809109/

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