Timeout a promise after a specified amount of time
Go to file
Sindre Sorhus dececa8aa3 3.2.0 2019-09-17 22:10:35 +07:00
.github Create funding.yml 2019-05-28 16:12:52 +07:00
.editorconfig Meta tweaks 2017-07-02 03:43:15 +02:00
.gitattributes Require Node.js 8, add TypeScript definition (#10) 2019-03-12 15:17:11 +07:00
.gitignore Meta tweaks 2017-07-02 03:43:15 +02:00
.npmrc Meta tweaks 2017-07-02 03:43:15 +02:00
.travis.yml Require Node.js 8, add TypeScript definition (#10) 2019-03-12 15:17:11 +07:00
index.d.ts Add support for passing in Infinity as `milliseconds` 2019-09-17 22:09:28 +07:00
index.js Add support for passing in Infinity as `milliseconds` 2019-09-17 22:09:28 +07:00
index.test-d.ts Refactor TypeScript definition to CommonJS compatible export (#11) 2019-04-04 11:58:41 +07:00
license Meta tweaks 2017-07-02 03:43:15 +02:00
package.json 3.2.0 2019-09-17 22:10:35 +07:00
readme.md Add support for passing in Infinity as `milliseconds` 2019-09-17 22:09:28 +07:00
test.js Add support for passing in Infinity as `milliseconds` 2019-09-17 22:09:28 +07:00

readme.md

p-timeout Build Status

Timeout a promise after a specified amount of time

Install

$ npm install p-timeout

Usage

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?)

pTimeout(input, milliseconds, fallback?)

Returns a decorated input that times out after milliseconds 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.

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:

const delay = require('delay');
const pTimeout = require('p-timeout');

const delayedPromise = () => delay(200);

pTimeout(delayedPromise(), 50, () => {
	return pTimeout(delayedPromise(), 300);
});

pTimeout.TimeoutError

Exposed for instance checking and sub-classing.

  • delay - Delay a promise a specified amount of time
  • p-min-delay - Delay a promise a minimum amount of time
  • p-retry - Retry a promise-returning function
  • More…