pax_global_header00006660000000000000000000000064137716121120014513gustar00rootroot0000000000000052 comment=4f86930f75d1565927790ab70b4ac643e47007fc p-timeout-4.1.0/000077500000000000000000000000001377161211200134405ustar00rootroot00000000000000p-timeout-4.1.0/.editorconfig000066400000000000000000000002571377161211200161210ustar00rootroot00000000000000root = true [*] indent_style = tab end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.yml] indent_style = space indent_size = 2 p-timeout-4.1.0/.gitattributes000066400000000000000000000000231377161211200163260ustar00rootroot00000000000000* text=auto eol=lf p-timeout-4.1.0/.github/000077500000000000000000000000001377161211200150005ustar00rootroot00000000000000p-timeout-4.1.0/.github/funding.yml000066400000000000000000000001331377161211200171520ustar00rootroot00000000000000github: sindresorhus open_collective: sindresorhus custom: https://sindresorhus.com/donate p-timeout-4.1.0/.github/workflows/000077500000000000000000000000001377161211200170355ustar00rootroot00000000000000p-timeout-4.1.0/.github/workflows/main.yml000066400000000000000000000006641377161211200205120ustar00rootroot00000000000000name: CI on: - push - pull_request jobs: test: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: node-version: - 14 - 12 - 10 steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} - run: npm install - run: npm test p-timeout-4.1.0/.gitignore000066400000000000000000000000271377161211200154270ustar00rootroot00000000000000node_modules yarn.lock p-timeout-4.1.0/.npmrc000066400000000000000000000000231377161211200145530ustar00rootroot00000000000000package-lock=false p-timeout-4.1.0/index.d.ts000066400000000000000000000063661377161211200153540ustar00rootroot00000000000000declare class TimeoutErrorClass extends Error { readonly name: 'TimeoutError'; constructor(message?: string); } declare namespace pTimeout { type TimeoutError = TimeoutErrorClass; type Options = { /** Custom implementations for the `setTimeout` and `clearTimeout` functions. Useful for testing purposes, in particular to work around [`sinon.useFakeTimers()`](https://sinonjs.org/releases/latest/fake-timers/). @example ``` import pTimeout = require('p-timeout'); import sinon = require('sinon'); (async () => { const originalSetTimeout = setTimeout; const originalClearTimeout = clearTimeout; sinon.useFakeTimers(); // Use `pTimeout` without being affected by `sinon.useFakeTimers()`: await pTimeout(doSomething(), 2000, undefined, { customTimers: { setTimeout: originalSetTimeout, clearTimeout: originalClearTimeout } }); })(); ``` */ readonly customTimers?: { setTimeout: typeof global.setTimeout; clearTimeout: typeof global.clearTimeout; }; }; } interface ClearablePromise extends Promise{ /** Clear the timeout. */ clear: () => void; } declare const pTimeout: { TimeoutError: typeof TimeoutErrorClass; default: typeof pTimeout; /** Timeout a promise after a specified amount of time. 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 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. It has a `.clear()` method that clears the timeout. @example ``` import delay = require('delay'); import pTimeout = require('p-timeout'); const delayedPromise = delay(200); pTimeout(delayedPromise, 50).then(() => 'foo'); //=> [TimeoutError: Promise timed out after 50 milliseconds] ``` */ ( input: PromiseLike, milliseconds: number, message?: string | Error, options?: pTimeout.Options ): ClearablePromise; /** Timeout a promise after a specified amount of time. 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. 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. It has a `.clear()` method that clears the timeout. @example ``` import delay = require('delay'); import pTimeout = require('p-timeout'); const delayedPromise = () => delay(200); pTimeout(delayedPromise(), 50, () => { return pTimeout(delayedPromise(), 300); }); ``` */ ( input: PromiseLike, milliseconds: number, fallback: () => ReturnType | Promise, options?: pTimeout.Options ): ClearablePromise; }; export = pTimeout; p-timeout-4.1.0/index.js000066400000000000000000000030271377161211200151070ustar00rootroot00000000000000'use strict'; class TimeoutError extends Error { constructor(message) { super(message); this.name = 'TimeoutError'; } } 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; } options = { customTimers: {setTimeout, clearTimeout}, ...options }; timer = options.customTimers.setTimeout.call(undefined, () => { if (typeof fallback === 'function') { try { resolve(fallback()); } catch (error) { reject(error); } return; } 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(); } reject(timeoutError); }, milliseconds); (async () => { try { resolve(await promise); } catch (error) { reject(error); } finally { options.customTimers.clearTimeout.call(undefined, timer); } })(); }); cancelablePromise.clear = () => { clearTimeout(timer); timer = undefined; }; return cancelablePromise; }; module.exports = pTimeout; // TODO: Remove this for the next major release module.exports.default = pTimeout; module.exports.TimeoutError = TimeoutError; p-timeout-4.1.0/index.test-d.ts000066400000000000000000000026571377161211200163300ustar00rootroot00000000000000import {expectType, expectError} from 'tsd'; import pTimeout = require('.'); import {TimeoutError} from '.'; const delayedPromise: () => Promise = async () => { return new Promise(resolve => { setTimeout(() => { resolve('foo'); }, 200); }); }; pTimeout(delayedPromise(), 50).then(() => 'foo'); pTimeout(delayedPromise(), 50, () => { return pTimeout(delayedPromise(), 300); }); pTimeout(delayedPromise(), 50).then(value => expectType(value)); pTimeout(delayedPromise(), 50, 'error').then(value => expectType(value) ); pTimeout(delayedPromise(), 50, new Error('error')).then(value => expectType(value) ); pTimeout(delayedPromise(), 50, async () => 10).then(value => { expectType(value); }); pTimeout(delayedPromise(), 50, () => 10).then(value => { expectType(value); }); const customTimers = {setTimeout, clearTimeout}; pTimeout(delayedPromise(), 50, undefined, {customTimers}); pTimeout(delayedPromise(), 50, 'foo', {customTimers}); pTimeout(delayedPromise(), 50, new Error('error'), {customTimers}); pTimeout(delayedPromise(), 50, () => 10, {}); expectError(pTimeout(delayedPromise(), 50, () => 10, {customTimers: {setTimeout}})); expectError(pTimeout(delayedPromise(), 50, () => 10, { customTimers: { setTimeout: () => 42, // Invalid `setTimeout` implementation clearTimeout } })); const timeoutError = new TimeoutError(); expectType(timeoutError); p-timeout-4.1.0/license000066400000000000000000000021351377161211200150060ustar00rootroot00000000000000MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. p-timeout-4.1.0/package.json000066400000000000000000000013611377161211200157270ustar00rootroot00000000000000{ "name": "p-timeout", "version": "4.1.0", "description": "Timeout a promise after a specified amount of time", "license": "MIT", "repository": "sindresorhus/p-timeout", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "engines": { "node": ">=10" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "promise", "timeout", "error", "invalidate", "async", "await", "promises", "time", "out", "cancel", "bluebird" ], "devDependencies": { "ava": "^2.4.0", "delay": "^4.4.0", "p-cancelable": "^2.0.0", "tsd": "^0.13.1", "xo": "^0.35.0", "in-range": "^2.0.0", "time-span": "^4.0.0" } } p-timeout-4.1.0/readme.md000066400000000000000000000051651377161211200152260ustar00rootroot00000000000000# p-timeout > Timeout a promise after a specified amount of time ## Install ``` $ npm install p-timeout ``` ## Usage ```js const delay = require('delay'); const pTimeout = require('p-timeout'); const delayedPromise = delay(200); pTimeout(delayedPromise, 50).then(() => 'foo'); //=> [TimeoutError: Promise timed out after 50 milliseconds] ``` ## API ### pTimeout(input, milliseconds, message?, options?) ### pTimeout(input, milliseconds, fallback?, options?) 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. #### input Type: `Promise` Promise to decorate. #### milliseconds Type: `number` Milliseconds before timing out. Passing `Infinity` will cause it to never time out. #### message Type: `string | Error`\ Default: `'Promise timed out after 50 milliseconds'` Specify a custom error message or error. If you do a custom error, it's recommended to sub-class `pTimeout.TimeoutError`. #### fallback Type: `Function` Do something other than rejecting with an error on timeout. You could for example retry: ```js const delay = require('delay'); const pTimeout = require('p-timeout'); const delayedPromise = () => delay(200); pTimeout(delayedPromise(), 50, () => { return pTimeout(delayedPromise(), 300); }); ``` #### options Type: `object` ##### customTimers Type: `object` with function properties `setTimeout` and `clearTimeout` Custom implementations for the `setTimeout` and `clearTimeout` functions. Useful for testing purposes, in particular to work around [`sinon.useFakeTimers()`](https://sinonjs.org/releases/latest/fake-timers/). Example: ```js const pTimeout = require('p-timeout'); const sinon = require('sinon'); (async () => { const originalSetTimeout = setTimeout; const originalClearTimeout = clearTimeout; sinon.useFakeTimers(); // Use `pTimeout` without being affected by `sinon.useFakeTimers()`: await pTimeout(doSomething(), 2000, undefined, { customTimers: { setTimeout: originalSetTimeout, clearTimeout: originalClearTimeout } }); })(); ``` ### pTimeout.TimeoutError Exposed for instance checking and sub-classing. ## Related - [delay](https://github.com/sindresorhus/delay) - Delay a promise a specified amount of time - [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) p-timeout-4.1.0/test.js000066400000000000000000000044441377161211200147630ustar00rootroot00000000000000import 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'); const fixtureError = new Error('fixture'); test('resolves before timeout', async t => { t.is(await pTimeout(delay(50).then(() => fixture), 200), fixture); }); test('throws when milliseconds is not number', async t => { await t.throwsAsync(pTimeout(delay(50), '200'), TypeError); }); 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); }); test('rejects before timeout if specified promise rejects', async t => { await t.throwsAsync(pTimeout(delay(50).then(() => Promise.reject(fixtureError)), 200), fixtureError.message); }); test('fallback argument', async t => { await t.throwsAsync(pTimeout(delay(200), 50, 'rainbow'), 'rainbow'); await t.throwsAsync(pTimeout(delay(200), 50, new RangeError('cake')), RangeError); await t.throwsAsync(pTimeout(delay(200), 50, () => Promise.reject(fixtureError)), fixtureError.message); await t.throwsAsync(pTimeout(delay(200), 50, () => { throw new RangeError('cake'); }), RangeError); }); test('calls `.cancel()` on promise when it exists', async t => { const promise = new PCancelable(async (resolve, reject, onCancel) => { onCancel(() => { t.pass(); }); await delay(200); resolve(); }); await t.throwsAsync(pTimeout(promise, 50), pTimeout.TimeoutError); t.true(promise.isCanceled); }); test('accepts `customTimers` option', async t => { t.plan(2); await pTimeout(delay(50), 123, undefined, { customTimers: { setTimeout(fn, milliseconds) { t.is(milliseconds, 123); return setTimeout(fn, milliseconds); }, clearTimeout(timeoutId) { t.pass(); return clearTimeout(timeoutId); } } }); }); 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})); });