Handle API timeouts in Node Sails.js I am working on a node.js sails.js app that handles a number of API calls and uses Bluebird for promises. The API calls have been reliable but I would like to build in handling for if they do not respond. I'm wondering if there is a good standard practice for handling timeouts (or a different approach) if the API services are down or do not respond.

Here is the code I have found/modified to work with, 15000 is a 15 second timeout on the API. Is this approach good, is there a better way?

var Promise = require('bluebird');        

return new Promise(function (resolve, reject) {
  //resolve my API call here.
})
.timeout(15000)
.cancellable()
.catch(Promise.CancellationError, function(error) {
  // ... must neatly abort the task ...
  console.log('Task cancelled', error);
})
.catch(Promise.TimeoutError, function(error) {
  // ... must neatly abort the task ...
  console.log('Task timed out', error);
});
The main issue I have with this code is that you're calling .timeout() on a Promise instance; by default, Promise doesn't support this - this is a Bluebird only operation. 

This means that your returned Promise must evaluate true for Promise &lt;: BluebirdPromise, which is not something that can be guaranteed in all environments (especially if you do what you've done here and omit the declaration for require('bluebird').

I'd prefer to see something like this:

const BluebirdPromise = require('bluebird');

return new BluebirdPromise(function (resolve, reject) {
  //resolve my API call here.
})
.timeout(15000)
.cancellable()
.catch(BluebirdPromise.CancellationError, function(error) {
  // ... must neatly abort the task ...
  console.log('Task cancelled', error);
})
.catch(BluebirdPromise.TimeoutError, function(error) {
  // ... must neatly abort the task ...
  console.log('Task timed out', error);
});


At the very least, this makes it clear that you aren't using the standard ES6 Promise, but that you're using a specific version from Bluebird.

I've not used the timeout and cancellable methods, so I can't speak for how you could code that better specifically, so there's probably more to say here.