aboutsummaryrefslogtreecommitdiff
path: root/node_modules/p-timeout/index.js
blob: 8393646a824acb8f65bace252c4f98a5d2f1f8a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
'use strict';
const pFinally = require('p-finally');

class TimeoutError extends Error {
	constructor(message) {
		super(message);
		this.name = 'TimeoutError';
	}
}

module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => {
	if (typeof ms !== 'number' || ms < 0) {
		throw new TypeError('Expected `ms` to be a positive number');
	}

	const timer = setTimeout(() => {
		if (typeof fallback === 'function') {
			try {
				resolve(fallback());
			} catch (err) {
				reject(err);
			}
			return;
		}

		const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${ms} milliseconds`;
		const err = fallback instanceof Error ? fallback : new TimeoutError(message);

		if (typeof promise.cancel === 'function') {
			promise.cancel();
		}

		reject(err);
	}, ms);

	pFinally(
		promise.then(resolve, reject),
		() => {
			clearTimeout(timer);
		}
	);
});

module.exports.TimeoutError = TimeoutError;