Full-Stack How to Integrate Intervals into a Promises Chain in Node.js?

You have Node.js program whose flow is based on promises, using promise chain. You need to use setInterval
. How do you integrate it with the rest of your flow, so you can use the standard promise chain?
We present a solution that will work in Node.js version v6.9.2 and up.
Promises
Promises greatly simplify your Node.js code involving asynchronous actions. When you get used to working with promises, you realize that you better make everything into a promise.
Intervals
If you work with setInterval
to poll for status, such as:
setInterval(() => {
testLongJobStatus(args).
.then((data) => { console.log(data); });
}, 1000);
How are you going to break out of the setInterval
and return a promise?
Make a Promise from setInterval
We create a new promise with resolve
and reject
parameters, and have setInterval
resolve or reject it:
const taskResolution = (args, period) => {
return new Promise((resolve, reject) => {
const interval = setInterval(() => {
testLongJobStatus(args)
.then((data) => {
if (data === 'failure') {
clearInterval(interval);
reject(Error('fail'));
} else if (data === 'success') {
resolve('complete')
}
// keep on waiting
});
}, period);
});
};
Once we receive a status from the long-running job, we resolve or reject.
Integrate the Interval with the Promises Chain
Because our function taskResolution
returns a promise, we are able to integrate it easily with the rest of our promise flow:
taskResolution(args, period)
.then((data) => {})
.catch((error) => {});
Yoram Kornatzky