All files / hof timed.js

100% Statements 6/6
50% Branches 1/2
100% Functions 3/3
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22    1x                 2x         2x 2x 2x      
import { sleep } from 'simple';
 
const DEFAULT_CONFIG = {
	task: 'promise resolution',
	timeout: 1000,
	context: null
};
 
// decorates a promise generating function such that if it takes too long to
// complete, it will time out.
export default function timed(asyncFn, config) {
	config = {
		...DEFAULT_CONFIG,
		...(config || {})
	};
 
	return function timedFn(...args) {
		const pacer = sleep(config.timeout).then(() => Promise.reject(new Error(`${config.task} timed out`)));
		return Promise.race([asyncFn.apply(config.context, args), pacer]);
	}
}