Using a promise to implement a timeout - throw an error
<p>I'm trying to implement a timeout for an asynchronous function using a promise and setTimeout. I want to run an asynchronous operation, and if it doesn't complete by a certain amount of time, throw an error. Currently, this is what I have: (some of it found on stackoverflow)</p>

<pre><code>function someOperation(cb) {
  setTimeout(function() {
    cb(null, 'Done');
  }, 2000);
}


var p = new Promise(function(resolve, reject) {
  setTimeout(function() {
    reject(new Error('Operation timed out'));
  }, 100);

  someOperation(function(err, res) {
    if (err) reject(err);
    else resolve(res);
  });

});

p.then(function(res) {
  console.log(res);
}, function(err) {
  console.log("Throwing error...")
  throw err;
});
</code></pre>

<p>But the program doesn't stop when the error is thrown. Would anybody be able to tell me why, and if there is an easier way to do this? I'd be very much appreciative. </p>

<p>EDIT: Now trying to use bluebird for the first time and it is giving someOperationPromised.timeout is not a function. Am I doing this correctly?</p>

<pre><code>var Promise = require("bluebird");

function someOperation(cb) {
  setTimeout(function() {
    cb('', 'Done');
  }, 2000);
}

var someOperationPromised = Promise.promisify(someOperation);

someOperationPromised.timeout(1).then(function (){
  console.log("Finished!");
}).catch(Promise.TimeoutError, function (err) {
  throw err;
});
</code></pre>