捕捉Bluebird中的setinterval函数中引发的错误
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函数内抛出的错误? 我无法弄清楚
如何捕获在setinterval函数内抛出的错误?
你不能。 这是一个asynchronouscallback,承诺不会捕获这些。 你可以明确地做try catch
(或Promise.try
),但这不是正确的解决scheme。 另见这里 。
我无法弄清楚
setInterval
不能和承诺一起使用,代表单个结果。 您的custFunc
不会在期限结束时返回承诺,这应该是。
通过将其重构为recursion解决scheme,可以使一切变得简单:
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
一点,将continue / break指示为返回值,而不是调用clearInterval
– 或者只是在execProg
进行recursion调用。
如果您依赖于setInterval
的稳定时间(不受asynchronous(!) calc
和execProg
函数的执行时间的影响),那么您可能需要立即调用Promise.delay
并在不再需要时取消它。 或者,实施一个准确的计时器 。