Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 17 additions & 22 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
6 changes: 4 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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');
});
});
});
Expand Down