Skip to content

Commit

Permalink
Make timeout clearable (#15)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
ilkerceng and sindresorhus committed Dec 26, 2020
1 parent 46c25ac commit e26f08d
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 43 deletions.
15 changes: 11 additions & 4 deletions index.d.ts
Expand Up @@ -40,6 +40,13 @@ declare namespace pTimeout {
};
}

interface ClearablePromise<T> extends Promise<T>{
/**
Clear the timeout.
*/
clear: () => void;
}

declare const pTimeout: {
TimeoutError: typeof TimeoutErrorClass;

Expand All @@ -53,7 +60,7 @@ declare const pTimeout: {
@param input - Promise to decorate.
@param milliseconds - Milliseconds before timing out.
@param message - Specify a custom error message or error. If you do a custom error, it's recommended to sub-class `pTimeout.TimeoutError`. Default: `'Promise timed out after 50 milliseconds'`.
@returns A decorated `input` that times out after `milliseconds` time.
@returns A decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
@example
```
Expand All @@ -71,7 +78,7 @@ declare const pTimeout: {
milliseconds: number,
message?: string | Error,
options?: pTimeout.Options
): Promise<ValueType>;
): ClearablePromise<ValueType>;

/**
Timeout a promise after a specified amount of time.
Expand All @@ -81,7 +88,7 @@ declare const pTimeout: {
@param input - Promise to decorate.
@param milliseconds - Milliseconds before timing out. Passing `Infinity` will cause it to never time out.
@param fallback - Do something other than rejecting with an error on timeout. You could for example retry.
@returns A decorated `input` that times out after `milliseconds` time.
@returns A decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
@example
```
Expand All @@ -100,7 +107,7 @@ declare const pTimeout: {
milliseconds: number,
fallback: () => ReturnType | Promise<ReturnType>,
options?: pTimeout.Options
): Promise<ValueType | ReturnType>;
): ClearablePromise<ValueType | ReturnType>;
};

export = pTimeout;
84 changes: 47 additions & 37 deletions index.js
Expand Up @@ -7,52 +7,62 @@ class TimeoutError extends Error {
}
}

const pTimeout = (promise, milliseconds, fallback, options) => new Promise((resolve, reject) => {
if (typeof milliseconds !== 'number' || milliseconds < 0) {
throw new TypeError('Expected `milliseconds` to be a positive number');
}
const pTimeout = (promise, milliseconds, fallback, options) => {
let timer;
const cancelablePromise = new Promise((resolve, reject) => {
if (typeof milliseconds !== 'number' || milliseconds < 0) {
throw new TypeError('Expected `milliseconds` to be a positive number');
}

if (milliseconds === Infinity) {
resolve(promise);
return;
}
if (milliseconds === Infinity) {
resolve(promise);
return;
}

options = {
customTimers: {setTimeout, clearTimeout},
...options
};
options = {
customTimers: {setTimeout, clearTimeout},
...options
};

const timer = options.customTimers.setTimeout.call(undefined, () => {
if (typeof fallback === 'function') {
try {
resolve(fallback());
} catch (error) {
reject(error);
timer = options.customTimers.setTimeout.call(undefined, () => {
if (typeof fallback === 'function') {
try {
resolve(fallback());
} catch (error) {
reject(error);
}

return;
}

return;
}
const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);

const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);
if (typeof promise.cancel === 'function') {
promise.cancel();
}

if (typeof promise.cancel === 'function') {
promise.cancel();
}
reject(timeoutError);
}, milliseconds);

(async () => {
try {
resolve(await promise);
} catch (error) {
reject(error);
} finally {
options.customTimers.clearTimeout.call(undefined, timer);
}
})();
});

reject(timeoutError);
}, milliseconds);
cancelablePromise.clear = () => {
clearTimeout(timer);
timer = undefined;
};

(async () => {
try {
resolve(await promise);
} catch (error) {
reject(error);
} finally {
options.customTimers.clearTimeout.call(undefined, timer);
}
})();
});
return cancelablePromise;
};

module.exports = pTimeout;
// TODO: Remove this for the next major release
Expand Down
4 changes: 3 additions & 1 deletion package.json
Expand Up @@ -37,6 +37,8 @@
"delay": "^4.4.0",
"p-cancelable": "^2.0.0",
"tsd": "^0.13.1",
"xo": "^0.35.0"
"xo": "^0.35.0",
"in-range": "^2.0.0",
"time-span": "^4.0.0"
}
}
2 changes: 1 addition & 1 deletion readme.md
Expand Up @@ -25,7 +25,7 @@ pTimeout(delayedPromise, 50).then(() => 'foo');
### pTimeout(input, milliseconds, message?, options?)
### pTimeout(input, milliseconds, fallback?, options?)

Returns a decorated `input` that times out after `milliseconds` time.
Returns a decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.

If you pass in a cancelable promise, specifically a promise with a `.cancel()` method, that method will be called when the `pTimeout` promise times out.

Expand Down
12 changes: 12 additions & 0 deletions test.js
@@ -1,6 +1,8 @@
import test from 'ava';
import delay from 'delay';
import PCancelable from 'p-cancelable';
import inRange from 'in-range';
import timeSpan from 'time-span';
import pTimeout from '.';

const fixture = Symbol('fixture');
Expand Down Expand Up @@ -72,3 +74,13 @@ test('accepts `customTimers` option', async t => {
}
});
});

test('`.clear()` method', async t => {
const end = timeSpan();
const promise = pTimeout(delay(300), 200);

promise.clear();

await promise;
t.true(inRange(end(), {start: 0, end: 350}));
});

0 comments on commit e26f08d

Please sign in to comment.