Bluebird: Best pattern for "interval with timeout" with bluebird

Created on 13 Oct 2015  路  2Comments  路  Source: petkaantonov/bluebird

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.

Most helpful comment

All 2 comments

Questions about usage should be posted on Stack Overflow or mailing list

Was this page helpful?
0 / 5 - 0 ratings