All files / src/hof timed.js

25% Statements 1/4
0% Branches 0/2
0% Functions 0/2
25% Lines 1/4
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    1x                                                
import Promise from 'bluebird';
 
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.
//
// WARNING: Do not mix with the throttled function above, because promises
// will take arbitrarily longer when throttled. At the very least, put the
// timed before throttling.
export default function timed(asyncFn, config) {
	config = {
		...DEFAULT_CONFIG,
		...(config || {})
	};
 
	return async function timedFn(...args) {
		return Promise.resolve(
			asyncFn.apply(config.context, args)
		).timeout(config.timeout, `${config.task} timed out`);
	}
}