I'm writing some code to do polling for a resource every N ms which should timeout after M seconds. I want the whole thing to be promise based using Bluebird as much as possible. The solution I've come up with so far uses node's interval, cancellable bluebird promises and bluebird's timeout function.
I'm wondering if there's a better way to do timing out intervals with bluebird?
var Promise = require('bluebird');
function poll() {
var interval;
return new Promise(function(resolve, reject) {
// This interval never resolves. Actual implementation could resolve.
interval = setInterval(function() {
console.log('Polling...')
}, 1000).unref();
})
.cancellable()
.catch(function(e) {
console.log('poll error:', e.name);
clearInterval(interval);
// Bubble up error
throw e;
});
}
function pollOrTimeout() {
return poll()
.then(function() {
return Promise.resolve('finished');
})
.timeout(5000)
.catch(Promise.TimeoutError, function(e) {
return Promise.resolve('timed out');
})
.catch(function(e) {
console.log('Got some other error');
throw e;
});
}
return pollOrTimeout()
.then(function(result) {
console.log('Result:', result);
});
Output:
Polling...
Polling...
Polling...
Polling...
poll error: TimeoutError
Result: timed out
I know this is not directly related to bluebird and more of a support question so thanks in advance for your help.
Questions about usage should be posted on Stack Overflow or mailing list
Posted here if anyone is interested: http://stackoverflow.com/questions/33222421/what-is-a-good-pattern-for-interval-with-timeout-using-promises
Most helpful comment
Posted here if anyone is interested: http://stackoverflow.com/questions/33222421/what-is-a-good-pattern-for-interval-with-timeout-using-promises