diff --git a/index.js b/index.js index 91b1bf8..ff37205 100644 --- a/index.js +++ b/index.js @@ -2,10 +2,16 @@ 'use strict'; /** - * Local reference to TimeoutError - * @private + * Exception indicating that the timeout expired. */ -var TimeoutError; +class TimeoutError extends Error { + constructor(timeoutMillis) { + super(`Promise did not resolve within ${timeoutMillis}ms`); + this.name = this.constructor.name; + Error.captureStackTrace(this, this.constructor); + } +} +exports.TimeoutError = TimeoutError; /** * Rejects a promise with a {@link TimeoutError} if it does not settle within @@ -16,34 +22,23 @@ var TimeoutError; * @returns {Promise} Either resolves/rejects with `promise`, or rejects with * `TimeoutError`, whichever settles first. */ -var timeout = module.exports.timeout = function(promise, timeoutMillis) { - var error = new TimeoutError(), - timeout; +function timeout(promise, timeoutMillis) { + let timeoutId; + const error = new TimeoutError(timeoutMillis); return Promise.race([ promise, new Promise(function(resolve, reject) { - timeout = setTimeout(function() { + timeoutId = setTimeout(function() { reject(error); }, timeoutMillis); }), ]).then(function(v) { - clearTimeout(timeout); + clearTimeout(timeoutId); return v; }, function(err) { - clearTimeout(timeout); + clearTimeout(timeoutId); throw err; }); -}; - -/** - * Exception indicating that the timeout expired. - */ -TimeoutError = module.exports.TimeoutError = function() { - Error.call(this) - this.stack = Error().stack - this.message = 'Timeout'; -}; - -TimeoutError.prototype = Object.create(Error.prototype); -TimeoutError.prototype.name = "TimeoutError"; +} +exports.timeout = timeout; diff --git a/test/test.js b/test/test.js index 5849d78..dcba448 100644 --- a/test/test.js +++ b/test/test.js @@ -1,8 +1,8 @@ // Copyright (c) 2015 David M. Lee, II 'use strict'; -var pt = require('../index.js'); -var assert = require('assert'); +const pt = require('../index.js'); +const assert = require('assert'); function later(when) { return new Promise(function(resolve, reject) { @@ -27,6 +27,8 @@ describe('promise-timeout', function() { assert.fail('should not have resolved'); }, function(err) { assert(err.stack.includes('test.js')); + assert(err.stack.startsWith('TimeoutError: Promise did not')); + assert.equal(err.name, 'TimeoutError'); }); }); });