gpt4 book ai didi

javascript - 捕获 Bluebird 中 setinterval 函数内部抛出的错误

转载 作者:太空宇宙 更新时间:2023-11-03 22:34:36 26 4
gpt4 key购买 nike

this.custFunc = Bluebird.method(function (id)) {

var interval = setInterval(function () {
calc(id)
.then(function (flag) {
if (flag) {
execProg(id, interval);
}
})
.catch(function (err) {
return Bluebird.reject(err);
});
}, pollingInterval);
});

如何捕获 setinterval 函数中抛出的错误?我无法弄清楚?

最佳答案

How do I catch the error being thrown inside the setinterval function?

你不能。这是一个异步回调,并且 Promise 不会捕获这些回调。您可以显式执行 try catch (或 Promise.try),但这不是正确的解决方案。另请参阅here .

I am not able to figure it out

setInterval 与代表单个结果的 Promise 不能很好地配合使用。您的 custFunc 不会返回间隔结束的 promise ,而它应该是这样。

您可以通过将其重构为递归解决方案来使一切变得更加简单:

this.custFunc = function(id) {
return Promise.delay(pollingInterval).then(function() {
return calc(id);
}).then(function(flag) {
if (flag) {
return execProg(id);
}
}).bind(this).then(function() {
if (/*you want to break the interval*/)
return result;
else
return this.custFunc(id);
});
});

您可能需要稍微重组 execProg 来发出继续/中断信号作为返回值,而不是通过调用 clearInterval - 或者只是从 execProg 中进行递归调用。

如果您依赖于setInterval的稳定计时(不受async(!) calcexecProg执行时间的影响函数),您可能想立即调用 Promise.delaycancel如果不再需要,请稍后再进行。或者,实现 accurate timer .

关于javascript - 捕获 Bluebird 中 setinterval 函数内部抛出的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31437603/

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