@common.js/p-timeout 5.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 ADDED
@@ -0,0 +1,5 @@
1
+ # @common.js/p-timeout
2
+
3
+ The [p-timeout](https://www.npmjs.com/package/p-timeout) package exported as CommonJS modules.
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.
package/index.d.ts ADDED
@@ -0,0 +1,126 @@
1
+ /* eslint-disable import/export */
2
+
3
+ export class TimeoutError extends Error {
4
+ readonly name: 'TimeoutError';
5
+ constructor(message?: string);
6
+ }
7
+
8
+ export interface ClearablePromise<T> extends Promise<T>{
9
+ /**
10
+ Clear the timeout.
11
+ */
12
+ clear: () => void;
13
+ }
14
+
15
+ export type Options = {
16
+ /**
17
+ Custom implementations for the `setTimeout` and `clearTimeout` functions.
18
+
19
+ Useful for testing purposes, in particular to work around [`sinon.useFakeTimers()`](https://sinonjs.org/releases/latest/fake-timers/).
20
+
21
+ @example
22
+ ```
23
+ import pTimeout from 'p-timeout';
24
+ import sinon from 'sinon';
25
+
26
+ const originalSetTimeout = setTimeout;
27
+ const originalClearTimeout = clearTimeout;
28
+
29
+ sinon.useFakeTimers();
30
+
31
+ // Use `pTimeout` without being affected by `sinon.useFakeTimers()`:
32
+ await pTimeout(doSomething(), 2000, undefined, {
33
+ customTimers: {
34
+ setTimeout: originalSetTimeout,
35
+ clearTimeout: originalClearTimeout
36
+ }
37
+ });
38
+ ```
39
+ */
40
+ readonly customTimers?: {
41
+ setTimeout: typeof global.setTimeout;
42
+ clearTimeout: typeof global.clearTimeout;
43
+ };
44
+
45
+ /**
46
+ You can abort the promise using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
47
+
48
+ _Requires Node.js 16 or later._
49
+
50
+ @example
51
+ ```
52
+ import pTimeout from 'p-timeout';
53
+ import delay from 'delay';
54
+
55
+ const delayedPromise = delay(3000);
56
+
57
+ const abortController = new AbortController();
58
+
59
+ setTimeout(() => {
60
+ abortController.abort();
61
+ }, 100);
62
+
63
+ await pTimeout(delayedPromise, 2000, undefined, {
64
+ signal: abortController.signal
65
+ });
66
+ ```
67
+ */
68
+ signal?: globalThis.AbortSignal;
69
+ };
70
+
71
+ /**
72
+ Timeout a promise after a specified amount of time.
73
+
74
+ 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
+
76
+ @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
+ @returns A decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
108
+
109
+ @example
110
+ ```
111
+ import {setTimeout} from 'timers/promises';
112
+ import pTimeout from 'p-timeout';
113
+
114
+ const delayedPromise = () => setTimeout(200);
115
+
116
+ await pTimeout(delayedPromise(), 50, () => {
117
+ return pTimeout(delayedPromise(), 300);
118
+ });
119
+ ```
120
+ */
121
+ export default function pTimeout<ValueType, ReturnType>(
122
+ input: PromiseLike<ValueType>,
123
+ milliseconds: number,
124
+ fallback: () => ReturnType | Promise<ReturnType>,
125
+ options?: Options
126
+ ): ClearablePromise<ValueType | ReturnType>;
package/index.js ADDED
@@ -0,0 +1,436 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ TimeoutError: function() {
13
+ return TimeoutError;
14
+ },
15
+ AbortError: function() {
16
+ return AbortError;
17
+ },
18
+ default: function() {
19
+ return pTimeout;
20
+ }
21
+ });
22
+ function _assertThisInitialized(self) {
23
+ if (self === void 0) {
24
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
25
+ }
26
+ return self;
27
+ }
28
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
29
+ try {
30
+ var info = gen[key](arg);
31
+ var value = info.value;
32
+ } catch (error) {
33
+ reject(error);
34
+ return;
35
+ }
36
+ if (info.done) {
37
+ resolve(value);
38
+ } else {
39
+ Promise.resolve(value).then(_next, _throw);
40
+ }
41
+ }
42
+ function _asyncToGenerator(fn) {
43
+ return function() {
44
+ var self = this, args = arguments;
45
+ return new Promise(function(resolve, reject) {
46
+ var gen = fn.apply(self, args);
47
+ function _next(value) {
48
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
49
+ }
50
+ function _throw(err) {
51
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
52
+ }
53
+ _next(undefined);
54
+ });
55
+ };
56
+ }
57
+ function _classCallCheck(instance, Constructor) {
58
+ if (!(instance instanceof Constructor)) {
59
+ throw new TypeError("Cannot call a class as a function");
60
+ }
61
+ }
62
+ function isNativeReflectConstruct() {
63
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
64
+ if (Reflect.construct.sham) return false;
65
+ if (typeof Proxy === "function") return true;
66
+ try {
67
+ Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
68
+ return true;
69
+ } catch (e) {
70
+ return false;
71
+ }
72
+ }
73
+ function _construct(Parent, args, Class) {
74
+ if (isNativeReflectConstruct()) {
75
+ _construct = Reflect.construct;
76
+ } else {
77
+ _construct = function _construct(Parent, args, Class) {
78
+ var a = [
79
+ null
80
+ ];
81
+ a.push.apply(a, args);
82
+ var Constructor = Function.bind.apply(Parent, a);
83
+ var instance = new Constructor();
84
+ if (Class) _setPrototypeOf(instance, Class.prototype);
85
+ return instance;
86
+ };
87
+ }
88
+ return _construct.apply(null, arguments);
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
+ function _getPrototypeOf(o) {
104
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
105
+ return o.__proto__ || Object.getPrototypeOf(o);
106
+ };
107
+ return _getPrototypeOf(o);
108
+ }
109
+ function _inherits(subClass, superClass) {
110
+ if (typeof superClass !== "function" && superClass !== null) {
111
+ throw new TypeError("Super expression must either be null or a function");
112
+ }
113
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
114
+ constructor: {
115
+ value: subClass,
116
+ writable: true,
117
+ configurable: true
118
+ }
119
+ });
120
+ if (superClass) _setPrototypeOf(subClass, superClass);
121
+ }
122
+ function _instanceof(left, right) {
123
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
124
+ return !!right[Symbol.hasInstance](left);
125
+ } else {
126
+ return left instanceof right;
127
+ }
128
+ }
129
+ function _isNativeFunction(fn) {
130
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
131
+ }
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
+ function _possibleConstructorReturn(self, call) {
148
+ if (call && (_typeof(call) === "object" || typeof call === "function")) {
149
+ return call;
150
+ }
151
+ return _assertThisInitialized(self);
152
+ }
153
+ function _setPrototypeOf(o, p) {
154
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
155
+ o.__proto__ = p;
156
+ return o;
157
+ };
158
+ return _setPrototypeOf(o, p);
159
+ }
160
+ var _typeof = function(obj) {
161
+ "@swc/helpers - typeof";
162
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
163
+ };
164
+ function _wrapNativeSuper(Class) {
165
+ var _cache = typeof Map === "function" ? new Map() : undefined;
166
+ _wrapNativeSuper = function _wrapNativeSuper(Class) {
167
+ if (Class === null || !_isNativeFunction(Class)) return Class;
168
+ if (typeof Class !== "function") {
169
+ throw new TypeError("Super expression must either be null or a function");
170
+ }
171
+ if (typeof _cache !== "undefined") {
172
+ if (_cache.has(Class)) return _cache.get(Class);
173
+ _cache.set(Class, Wrapper);
174
+ }
175
+ function Wrapper() {
176
+ return _construct(Class, arguments, _getPrototypeOf(this).constructor);
177
+ }
178
+ Wrapper.prototype = Object.create(Class.prototype, {
179
+ constructor: {
180
+ value: Wrapper,
181
+ enumerable: false,
182
+ writable: true,
183
+ configurable: true
184
+ }
185
+ });
186
+ return _setPrototypeOf(Wrapper, Class);
187
+ };
188
+ return _wrapNativeSuper(Class);
189
+ }
190
+ function _isNativeReflectConstruct() {
191
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
192
+ if (Reflect.construct.sham) return false;
193
+ if (typeof Proxy === "function") return true;
194
+ try {
195
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
196
+ return true;
197
+ } catch (e) {
198
+ return false;
199
+ }
200
+ }
201
+ function _createSuper(Derived) {
202
+ var hasNativeReflectConstruct = _isNativeReflectConstruct();
203
+ return function _createSuperInternal() {
204
+ var Super = _getPrototypeOf(Derived), result;
205
+ if (hasNativeReflectConstruct) {
206
+ var NewTarget = _getPrototypeOf(this).constructor;
207
+ result = Reflect.construct(Super, arguments, NewTarget);
208
+ } else {
209
+ result = Super.apply(this, arguments);
210
+ }
211
+ return _possibleConstructorReturn(this, result);
212
+ };
213
+ }
214
+ var __generator = (void 0) && (void 0).__generator || function(thisArg, body) {
215
+ var f, y, t, g, _ = {
216
+ label: 0,
217
+ sent: function() {
218
+ if (t[0] & 1) throw t[1];
219
+ return t[1];
220
+ },
221
+ trys: [],
222
+ ops: []
223
+ };
224
+ return g = {
225
+ next: verb(0),
226
+ "throw": verb(1),
227
+ "return": verb(2)
228
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
229
+ return this;
230
+ }), g;
231
+ function verb(n) {
232
+ return function(v) {
233
+ return step([
234
+ n,
235
+ v
236
+ ]);
237
+ };
238
+ }
239
+ function step(op) {
240
+ if (f) throw new TypeError("Generator is already executing.");
241
+ while(_)try {
242
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
243
+ if (y = 0, t) op = [
244
+ op[0] & 2,
245
+ t.value
246
+ ];
247
+ switch(op[0]){
248
+ case 0:
249
+ case 1:
250
+ t = op;
251
+ break;
252
+ case 4:
253
+ _.label++;
254
+ return {
255
+ value: op[1],
256
+ done: false
257
+ };
258
+ case 5:
259
+ _.label++;
260
+ y = op[1];
261
+ op = [
262
+ 0
263
+ ];
264
+ continue;
265
+ case 7:
266
+ op = _.ops.pop();
267
+ _.trys.pop();
268
+ continue;
269
+ default:
270
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
271
+ _ = 0;
272
+ continue;
273
+ }
274
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
275
+ _.label = op[1];
276
+ break;
277
+ }
278
+ if (op[0] === 6 && _.label < t[1]) {
279
+ _.label = t[1];
280
+ t = op;
281
+ break;
282
+ }
283
+ if (t && _.label < t[2]) {
284
+ _.label = t[2];
285
+ _.ops.push(op);
286
+ break;
287
+ }
288
+ if (t[2]) _.ops.pop();
289
+ _.trys.pop();
290
+ continue;
291
+ }
292
+ op = body.call(thisArg, _);
293
+ } catch (e) {
294
+ op = [
295
+ 6,
296
+ e
297
+ ];
298
+ y = 0;
299
+ } finally{
300
+ f = t = 0;
301
+ }
302
+ if (op[0] & 5) throw op[1];
303
+ return {
304
+ value: op[0] ? op[1] : void 0,
305
+ done: true
306
+ };
307
+ }
308
+ };
309
+ var TimeoutError = /*#__PURE__*/ function(Error1) {
310
+ "use strict";
311
+ _inherits(TimeoutError, Error1);
312
+ var _super = _createSuper(TimeoutError);
313
+ function TimeoutError(message) {
314
+ _classCallCheck(this, TimeoutError);
315
+ var _this;
316
+ _this = _super.call(this, message);
317
+ _this.name = "TimeoutError";
318
+ return _this;
319
+ }
320
+ return TimeoutError;
321
+ }(_wrapNativeSuper(Error));
322
+ var AbortError = /*#__PURE__*/ function(Error1) {
323
+ "use strict";
324
+ _inherits(AbortError, Error1);
325
+ var _super = _createSuper(AbortError);
326
+ function AbortError(message) {
327
+ _classCallCheck(this, AbortError);
328
+ var _this;
329
+ _this = _super.call(this);
330
+ _this.name = "AbortError";
331
+ _this.message = message;
332
+ return _this;
333
+ }
334
+ return AbortError;
335
+ }(_wrapNativeSuper(Error));
336
+ /**
337
+ TODO: Remove AbortError and just throw DOMException when targeting Node 18.
338
+ */ var getDOMException = function(errorMessage) {
339
+ return globalThis.DOMException === undefined ? new AbortError(errorMessage) : new DOMException(errorMessage);
340
+ };
341
+ /**
342
+ TODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.
343
+ */ var getAbortedReason = function(signal) {
344
+ var reason = signal.reason === undefined ? getDOMException("This operation was aborted.") : signal.reason;
345
+ return _instanceof(reason, Error) ? reason : getDOMException(reason);
346
+ };
347
+ function pTimeout(promise, milliseconds, fallback, options) {
348
+ var timer;
349
+ var cancelablePromise = new Promise(function(resolve, reject) {
350
+ if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) {
351
+ throw new TypeError("Expected `milliseconds` to be a positive number, got `".concat(milliseconds, "`"));
352
+ }
353
+ if (milliseconds === Number.POSITIVE_INFINITY) {
354
+ resolve(promise);
355
+ return;
356
+ }
357
+ options = _objectSpread({
358
+ customTimers: {
359
+ setTimeout: setTimeout,
360
+ clearTimeout: clearTimeout
361
+ }
362
+ }, options);
363
+ if (options.signal) {
364
+ var signal = options.signal;
365
+ if (signal.aborted) {
366
+ reject(getAbortedReason(signal));
367
+ }
368
+ signal.addEventListener("abort", function() {
369
+ reject(getAbortedReason(signal));
370
+ });
371
+ }
372
+ timer = options.customTimers.setTimeout.call(undefined, function() {
373
+ if (typeof fallback === "function") {
374
+ try {
375
+ resolve(fallback());
376
+ } catch (error) {
377
+ reject(error);
378
+ }
379
+ return;
380
+ }
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
+ if (typeof promise.cancel === "function") {
384
+ promise.cancel();
385
+ }
386
+ reject(timeoutError);
387
+ }, milliseconds);
388
+ _asyncToGenerator(function() {
389
+ var error;
390
+ return __generator(this, function(_state) {
391
+ switch(_state.label){
392
+ case 0:
393
+ _state.trys.push([
394
+ 0,
395
+ 2,
396
+ 3,
397
+ 4
398
+ ]);
399
+ return [
400
+ 4,
401
+ promise
402
+ ];
403
+ case 1:
404
+ resolve.apply(void 0, [
405
+ _state.sent()
406
+ ]);
407
+ return [
408
+ 3,
409
+ 4
410
+ ];
411
+ case 2:
412
+ error = _state.sent();
413
+ reject(error);
414
+ return [
415
+ 3,
416
+ 4
417
+ ];
418
+ case 3:
419
+ options.customTimers.clearTimeout.call(undefined, timer);
420
+ return [
421
+ 7
422
+ ];
423
+ case 4:
424
+ return [
425
+ 2
426
+ ];
427
+ }
428
+ });
429
+ })();
430
+ });
431
+ cancelablePromise.clear = function() {
432
+ clearTimeout(timer);
433
+ timer = undefined;
434
+ };
435
+ return cancelablePromise;
436
+ }
package/license ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
4
+
5
+ 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:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ 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.
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@common.js/p-timeout",
3
+ "version": "5.1.0",
4
+ "description": "Timeout a promise after a specified amount of time",
5
+ "license": "MIT",
6
+ "repository": "etienne-martin/common.js",
7
+ "funding": "https://github.com/sponsors/sindresorhus",
8
+ "type": "commonjs",
9
+ "engines": {
10
+ "node": ">=12"
11
+ },
12
+ "scripts": {
13
+ "test": "xo && ava && tsd"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "index.d.ts"
18
+ ],
19
+ "devDependencies": {
20
+ "ava": "^3.15.0",
21
+ "delay": "^5.0.0",
22
+ "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"
27
+ },
28
+ "homepage": "https://github.com/etienne-martin/common.js#readme",
29
+ "dependencies": {},
30
+ "main": "./index.js"
31
+ }
package/readme.md ADDED
@@ -0,0 +1,140 @@
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)