@common.js/p-timeout 5.1.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,4 +2,4 @@
2
2
 
3
3
  The [p-timeout](https://www.npmjs.com/package/p-timeout) package exported as CommonJS modules.
4
4
 
5
- Exported from [p-timeout@5.1.0](https://www.npmjs.com/package/p-timeout/v/5.1.0) using https://github.com/etienne-martin/common.js.
5
+ Exported from [p-timeout@6.1.0](https://www.npmjs.com/package/p-timeout/v/6.1.0) using https://github.com/etienne-martin/common.js.
package/index.d.ts CHANGED
@@ -1,18 +1,66 @@
1
- /* eslint-disable import/export */
2
-
3
1
  export class TimeoutError extends Error {
4
2
  readonly name: 'TimeoutError';
5
3
  constructor(message?: string);
6
4
  }
7
5
 
8
- export interface ClearablePromise<T> extends Promise<T>{
6
+ export interface ClearablePromise<T> extends Promise<T> {
9
7
  /**
10
8
  Clear the timeout.
11
9
  */
12
10
  clear: () => void;
13
11
  }
14
12
 
15
- export type Options = {
13
+ export type Options<ReturnType> = {
14
+ /**
15
+ Milliseconds before timing out.
16
+
17
+ Passing `Infinity` will cause it to never time out.
18
+ */
19
+ milliseconds: number;
20
+
21
+ /**
22
+ Do something other than rejecting with an error on timeout.
23
+
24
+ You could for example retry:
25
+
26
+ @example
27
+ ```
28
+ import {setTimeout} from 'node:timers/promises';
29
+ import pTimeout from 'p-timeout';
30
+
31
+ const delayedPromise = () => setTimeout(200);
32
+
33
+ await pTimeout(delayedPromise(), {
34
+ milliseconds: 50,
35
+ fallback: () => {
36
+ return pTimeout(delayedPromise(), {
37
+ milliseconds: 300
38
+ });
39
+ },
40
+ });
41
+ ```
42
+ */
43
+ fallback?: () => ReturnType | Promise<ReturnType>;
44
+
45
+ /**
46
+ Specify a custom error message or error to throw when it times out:
47
+
48
+ - `message: 'too slow'` will throw `TimeoutError('too slow')`
49
+ - `message: new MyCustomError('it’s over 9000')` will throw the same error instance
50
+ - `message: false` will make the promise resolve with `undefined` instead of rejecting
51
+
52
+ If you do a custom error, it's recommended to sub-class `TimeoutError`:
53
+
54
+ ```
55
+ import {TimeoutError} from 'p-timeout';
56
+
57
+ class MyCustomError extends TimeoutError {
58
+ name = "MyCustomError";
59
+ }
60
+ ```
61
+ */
62
+ message?: string | Error | false;
63
+
16
64
  /**
17
65
  Custom implementations for the `setTimeout` and `clearTimeout` functions.
18
66
 
@@ -29,7 +77,8 @@ export type Options = {
29
77
  sinon.useFakeTimers();
30
78
 
31
79
  // Use `pTimeout` without being affected by `sinon.useFakeTimers()`:
32
- await pTimeout(doSomething(), 2000, undefined, {
80
+ await pTimeout(doSomething(), {
81
+ milliseconds: 2000,
33
82
  customTimers: {
34
83
  setTimeout: originalSetTimeout,
35
84
  clearTimeout: originalClearTimeout
@@ -38,8 +87,8 @@ export type Options = {
38
87
  ```
39
88
  */
40
89
  readonly customTimers?: {
41
- setTimeout: typeof global.setTimeout;
42
- clearTimeout: typeof global.clearTimeout;
90
+ setTimeout: typeof globalThis.setTimeout;
91
+ clearTimeout: typeof globalThis.clearTimeout;
43
92
  };
44
93
 
45
94
  /**
@@ -60,7 +109,8 @@ export type Options = {
60
109
  abortController.abort();
61
110
  }, 100);
62
111
 
63
- await pTimeout(delayedPromise, 2000, undefined, {
112
+ await pTimeout(delayedPromise, {
113
+ milliseconds: 2000,
64
114
  signal: abortController.signal
65
115
  });
66
116
  ```
@@ -74,53 +124,28 @@ Timeout a promise after a specified amount of time.
74
124
  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.
75
125
 
76
126
  @param input - Promise to decorate.
77
- @param milliseconds - Milliseconds before timing out.
78
- @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'`.
79
- @returns A decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
80
-
81
- @example
82
- ```
83
- import {setTimeout} from 'timers/promises';
84
- import pTimeout from 'p-timeout';
85
-
86
- const delayedPromise = setTimeout(200);
87
-
88
- await pTimeout(delayedPromise, 50);
89
- //=> [TimeoutError: Promise timed out after 50 milliseconds]
90
- ```
91
- */
92
- export default function pTimeout<ValueType>(
93
- input: PromiseLike<ValueType>,
94
- milliseconds: number,
95
- message?: string | Error,
96
- options?: Options
97
- ): ClearablePromise<ValueType>;
98
-
99
- /**
100
- Timeout a promise after a specified amount of time.
101
-
102
- 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.
103
-
104
- @param input - Promise to decorate.
105
- @param milliseconds - Milliseconds before timing out. Passing `Infinity` will cause it to never time out.
106
- @param fallback - Do something other than rejecting with an error on timeout. You could for example retry.
107
127
  @returns A decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
108
128
 
109
129
  @example
110
130
  ```
111
- import {setTimeout} from 'timers/promises';
131
+ import {setTimeout} from 'node:timers/promises';
112
132
  import pTimeout from 'p-timeout';
113
133
 
114
134
  const delayedPromise = () => setTimeout(200);
115
135
 
116
- await pTimeout(delayedPromise(), 50, () => {
117
- return pTimeout(delayedPromise(), 300);
136
+ await pTimeout(delayedPromise(), {
137
+ milliseconds: 50,
138
+ fallback: () => {
139
+ return pTimeout(delayedPromise(), 300);
140
+ }
118
141
  });
119
142
  ```
120
143
  */
121
- export default function pTimeout<ValueType, ReturnType>(
144
+ export default function pTimeout<ValueType, ReturnType = ValueType>(
145
+ input: PromiseLike<ValueType>,
146
+ options: Options<ReturnType> & {message: false}
147
+ ): ClearablePromise<ValueType | ReturnType | undefined>;
148
+ export default function pTimeout<ValueType, ReturnType = ValueType>(
122
149
  input: PromiseLike<ValueType>,
123
- milliseconds: number,
124
- fallback: () => ReturnType | Promise<ReturnType>,
125
- options?: Options
150
+ options: Options<ReturnType>
126
151
  ): ClearablePromise<ValueType | ReturnType>;
package/index.js CHANGED
@@ -87,19 +87,6 @@ function _construct(Parent, args, Class) {
87
87
  }
88
88
  return _construct.apply(null, arguments);
89
89
  }
90
- function _defineProperty(obj, key, value) {
91
- if (key in obj) {
92
- Object.defineProperty(obj, key, {
93
- value: value,
94
- enumerable: true,
95
- configurable: true,
96
- writable: true
97
- });
98
- } else {
99
- obj[key] = value;
100
- }
101
- return obj;
102
- }
103
90
  function _getPrototypeOf(o) {
104
91
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
105
92
  return o.__proto__ || Object.getPrototypeOf(o);
@@ -129,21 +116,6 @@ function _instanceof(left, right) {
129
116
  function _isNativeFunction(fn) {
130
117
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
131
118
  }
132
- function _objectSpread(target) {
133
- for(var i = 1; i < arguments.length; i++){
134
- var source = arguments[i] != null ? arguments[i] : {};
135
- var ownKeys = Object.keys(source);
136
- if (typeof Object.getOwnPropertySymbols === "function") {
137
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
138
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
139
- }));
140
- }
141
- ownKeys.forEach(function(key) {
142
- _defineProperty(target, key, source[key]);
143
- });
144
- }
145
- return target;
146
- }
147
119
  function _possibleConstructorReturn(self, call) {
148
120
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
149
121
  return call;
@@ -344,7 +316,11 @@ TODO: Remove below function and just 'reject(signal.reason)' when targeting Node
344
316
  var reason = signal.reason === undefined ? getDOMException("This operation was aborted.") : signal.reason;
345
317
  return _instanceof(reason, Error) ? reason : getDOMException(reason);
346
318
  };
347
- function pTimeout(promise, milliseconds, fallback, options) {
319
+ function pTimeout(promise, options) {
320
+ var milliseconds = options.milliseconds, fallback = options.fallback, message = options.message, _customTimers = options.customTimers, customTimers = _customTimers === void 0 ? {
321
+ setTimeout: setTimeout,
322
+ clearTimeout: clearTimeout
323
+ } : _customTimers;
348
324
  var timer;
349
325
  var cancelablePromise = new Promise(function(resolve, reject) {
350
326
  if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) {
@@ -354,12 +330,6 @@ function pTimeout(promise, milliseconds, fallback, options) {
354
330
  resolve(promise);
355
331
  return;
356
332
  }
357
- options = _objectSpread({
358
- customTimers: {
359
- setTimeout: setTimeout,
360
- clearTimeout: clearTimeout
361
- }
362
- }, options);
363
333
  if (options.signal) {
364
334
  var signal = options.signal;
365
335
  if (signal.aborted) {
@@ -369,8 +339,8 @@ function pTimeout(promise, milliseconds, fallback, options) {
369
339
  reject(getAbortedReason(signal));
370
340
  });
371
341
  }
372
- timer = options.customTimers.setTimeout.call(undefined, function() {
373
- if (typeof fallback === "function") {
342
+ timer = customTimers.setTimeout.call(undefined, function() {
343
+ if (fallback) {
374
344
  try {
375
345
  resolve(fallback());
376
346
  } catch (error) {
@@ -378,12 +348,17 @@ function pTimeout(promise, milliseconds, fallback, options) {
378
348
  }
379
349
  return;
380
350
  }
381
- var message = typeof fallback === "string" ? fallback : "Promise timed out after ".concat(milliseconds, " milliseconds");
382
- var timeoutError = _instanceof(fallback, Error) ? fallback : new TimeoutError(message);
383
351
  if (typeof promise.cancel === "function") {
384
352
  promise.cancel();
385
353
  }
386
- reject(timeoutError);
354
+ if (message === false) {
355
+ resolve();
356
+ } else if (_instanceof(message, Error)) {
357
+ reject(message);
358
+ } else {
359
+ var errorMessage = message !== null && message !== void 0 ? message : "Promise timed out after ".concat(milliseconds, " milliseconds");
360
+ reject(new TimeoutError(errorMessage));
361
+ }
387
362
  }, milliseconds);
388
363
  _asyncToGenerator(function() {
389
364
  var error;
@@ -416,7 +391,7 @@ function pTimeout(promise, milliseconds, fallback, options) {
416
391
  4
417
392
  ];
418
393
  case 3:
419
- options.customTimers.clearTimeout.call(undefined, timer);
394
+ customTimers.clearTimeout.call(undefined, timer);
420
395
  return [
421
396
  7
422
397
  ];
@@ -429,7 +404,7 @@ function pTimeout(promise, milliseconds, fallback, options) {
429
404
  })();
430
405
  });
431
406
  cancelablePromise.clear = function() {
432
- clearTimeout(timer);
407
+ customTimers.clearTimeout.call(undefined, timer);
433
408
  timer = undefined;
434
409
  };
435
410
  return cancelablePromise;
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@common.js/p-timeout",
3
- "version": "5.1.0",
4
- "description": "Timeout a promise after a specified amount of time",
3
+ "version": "6.1.0",
4
+ "description": "p-timeout package exported as CommonJS modules",
5
5
  "license": "MIT",
6
6
  "repository": "etienne-martin/common.js",
7
7
  "funding": "https://github.com/sponsors/sindresorhus",
8
8
  "type": "commonjs",
9
+ "types": "./index.d.ts",
9
10
  "engines": {
10
- "node": ">=12"
11
+ "node": ">=14.16"
11
12
  },
12
13
  "scripts": {
13
14
  "test": "xo && ava && tsd"
@@ -17,13 +18,13 @@
17
18
  "index.d.ts"
18
19
  ],
19
20
  "devDependencies": {
20
- "ava": "^3.15.0",
21
+ "ava": "^4.3.1",
21
22
  "delay": "^5.0.0",
22
23
  "in-range": "^3.0.0",
23
- "p-cancelable": "^2.1.0",
24
- "time-span": "^4.0.0",
25
- "tsd": "^0.14.0",
26
- "xo": "^0.38.2"
24
+ "p-cancelable": "^4.0.1",
25
+ "time-span": "^5.1.0",
26
+ "tsd": "^0.22.0",
27
+ "xo": "^0.51.0"
27
28
  },
28
29
  "homepage": "https://github.com/etienne-martin/common.js#readme",
29
30
  "dependencies": {},
package/readme.md DELETED
@@ -1,140 +0,0 @@
1
- # p-timeout
2
-
3
- > Timeout a promise after a specified amount of time
4
-
5
- ## Install
6
-
7
- ```
8
- $ npm install p-timeout
9
- ```
10
-
11
- ## Usage
12
-
13
- ```js
14
- import {setTimeout} from 'timers/promises';
15
- import pTimeout from 'p-timeout';
16
-
17
- const delayedPromise = setTimeout(200);
18
-
19
- await pTimeout(delayedPromise, 50);
20
- //=> [TimeoutError: Promise timed out after 50 milliseconds]
21
- ```
22
-
23
- ## API
24
-
25
- ### pTimeout(input, milliseconds, message?, options?)
26
- ### pTimeout(input, milliseconds, fallback?, options?)
27
-
28
- Returns a decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
29
-
30
- 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.
31
-
32
- #### input
33
-
34
- Type: `Promise`
35
-
36
- Promise to decorate.
37
-
38
- #### milliseconds
39
-
40
- Type: `number`
41
-
42
- Milliseconds before timing out.
43
-
44
- Passing `Infinity` will cause it to never time out.
45
-
46
- #### message
47
-
48
- Type: `string | Error`\
49
- Default: `'Promise timed out after 50 milliseconds'`
50
-
51
- Specify a custom error message or error.
52
-
53
- If you do a custom error, it's recommended to sub-class `pTimeout.TimeoutError`.
54
-
55
- #### fallback
56
-
57
- Type: `Function`
58
-
59
- Do something other than rejecting with an error on timeout.
60
-
61
- You could for example retry:
62
-
63
- ```js
64
- import {setTimeout} from 'timers/promises';
65
- import pTimeout from 'p-timeout';
66
-
67
- const delayedPromise = () => setTimeout(200);
68
-
69
- await pTimeout(delayedPromise(), 50, () => {
70
- return pTimeout(delayedPromise(), 300);
71
- });
72
- ```
73
-
74
- #### options
75
-
76
- Type: `object`
77
-
78
- ##### customTimers
79
-
80
- Type: `object` with function properties `setTimeout` and `clearTimeout`
81
-
82
- Custom implementations for the `setTimeout` and `clearTimeout` functions.
83
-
84
- Useful for testing purposes, in particular to work around [`sinon.useFakeTimers()`](https://sinonjs.org/releases/latest/fake-timers/).
85
-
86
- Example:
87
-
88
- ```js
89
- import {setTimeout} from 'timers/promises';
90
- import pTimeout from 'p-timeout';
91
-
92
- const originalSetTimeout = setTimeout;
93
- const originalClearTimeout = clearTimeout;
94
-
95
- sinon.useFakeTimers();
96
-
97
- // Use `pTimeout` without being affected by `sinon.useFakeTimers()`:
98
- await pTimeout(doSomething(), 2000, undefined, {
99
- customTimers: {
100
- setTimeout: originalSetTimeout,
101
- clearTimeout: originalClearTimeout
102
- }
103
- });
104
- ```
105
-
106
- #### signal
107
-
108
- Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
109
-
110
- You can abort the promise using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
111
-
112
- *Requires Node.js 16 or later.*
113
-
114
- ```js
115
- import pTimeout from 'p-timeout';
116
- import delay from 'delay';
117
-
118
- const delayedPromise = delay(3000);
119
-
120
- const abortController = new AbortController();
121
-
122
- setTimeout(() => {
123
- abortController.abort();
124
- }, 100);
125
-
126
- await pTimeout(delayedPromise, 2000, undefined, {
127
- signal: abortController.signal
128
- });
129
- ```
130
-
131
- ### TimeoutError
132
-
133
- Exposed for instance checking and sub-classing.
134
-
135
- ## Related
136
-
137
- - [delay](https://github.com/sindresorhus/delay) - Delay a promise a specified amount of time
138
- - [p-min-delay](https://github.com/sindresorhus/p-min-delay) - Delay a promise a minimum amount of time
139
- - [p-retry](https://github.com/sindresorhus/p-retry) - Retry a promise-returning function
140
- - [More…](https://github.com/sindresorhus/promise-fun)