Add support for passing in Infinity as `milliseconds`

Fixes #14
This commit is contained in:
Sindre Sorhus 2019-09-17 22:09:28 +07:00
parent 280144779b
commit a233d8cd1d
4 changed files with 17 additions and 7 deletions

2
index.d.ts vendored
View File

@ -41,7 +41,7 @@ declare const pTimeout: {
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.
@param input - Promise to decorate.
@param milliseconds - Milliseconds before timing out.
@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.

View File

@ -14,6 +14,11 @@ const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reje
throw new TypeError('Expected `milliseconds` to be a positive number');
}
if (milliseconds === Infinity) {
resolve(promise);
return;
}
const timer = setTimeout(() => {
if (typeof fallback === 'function') {
try {

View File

@ -25,7 +25,8 @@ pTimeout(delayedPromise, 50).then(() => 'foo');
## API
### pTimeout(input, milliseconds, [message | fallback])
### pTimeout(input, milliseconds, message?)
### pTimeout(input, milliseconds, fallback?)
Returns a decorated `input` that times out after `milliseconds` time.
@ -43,6 +44,8 @@ Type: `number`
Milliseconds before timing out.
Passing `Infinity` will cause it to never time out.
#### message
Type: `string` `Error`<br>
@ -82,8 +85,3 @@ Exposed for instance checking and sub-classing.
- [p-min-delay](https://github.com/sindresorhus/p-min-delay) - Delay a promise a minimum amount of time
- [p-retry](https://github.com/sindresorhus/p-retry) - Retry a promise-returning function
- [More…](https://github.com/sindresorhus/promise-fun)
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@ -18,6 +18,13 @@ test('throws when milliseconds is negative number', async t => {
await t.throwsAsync(pTimeout(delay(50), -1), TypeError);
});
test('handles milliseconds being `Infinity`', async t => {
t.is(
await pTimeout(delay(50, {value: fixture}), Infinity),
fixture
);
});
test('rejects after timeout', async t => {
await t.throwsAsync(pTimeout(delay(200), 50), pTimeout.TimeoutError);
});