From a233d8cd1dd2fe38aa717cac7d6ec6ff4db78d0a Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Tue, 17 Sep 2019 22:09:28 +0700 Subject: [PATCH] Add support for passing in Infinity as `milliseconds` Fixes #14 --- index.d.ts | 2 +- index.js | 5 +++++ readme.md | 10 ++++------ test.js | 7 +++++++ 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/index.d.ts b/index.d.ts index cd3dbbd..57d909f 100644 --- a/index.d.ts +++ b/index.d.ts @@ -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. diff --git a/index.js b/index.js index e8ca13d..34d4a4c 100644 --- a/index.js +++ b/index.js @@ -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 { diff --git a/readme.md b/readme.md index 8aec5ab..ad4ab52 100644 --- a/readme.md +++ b/readme.md @@ -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`
@@ -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) diff --git a/test.js b/test.js index 0ab8089..4d6ba10 100644 --- a/test.js +++ b/test.js @@ -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); });