How do I catch the error being thrown inside the setinterval function?
You cannot. It's an asynchronous callback, and promises don't catch those. You could be explicitly doing try catch
(or Promise.try
), but that's not the right solution. See also here.
I am not able to figure it out
setInterval
doesn't work well together with promises, which represent a single result. Your custFunc
doesn't return a promise for the end of the interval, which it is supposed to be.
You can make everything much simpler by refactoring this to a recursive solution:
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);
});
});
You might need to restructure execProg
a bit to signal continue/break as a return value instead of by calling clearInterval
- or alternatively just make the recursive call from within execProg
.
If you depend on the steady timing of setInterval
(without being influenced by the execution time of the async(!) calc
and execProg
functions), you might want to call Promise.delay
immediately and cancel it later if no longer needed. Alternatively, implement an accurate timer.