timeout.js
1 'use strict'; 2 3 Object.defineProperty(exports, "__esModule", { 4 value: true 5 }); 6 exports.default = timeout; 7 8 var _initialParams = require('./internal/initialParams'); 9 10 var _initialParams2 = _interopRequireDefault(_initialParams); 11 12 var _wrapAsync = require('./internal/wrapAsync'); 13 14 var _wrapAsync2 = _interopRequireDefault(_wrapAsync); 15 16 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 17 18 /** 19 * Sets a time limit on an asynchronous function. If the function does not call 20 * its callback within the specified milliseconds, it will be called with a 21 * timeout error. The code property for the error object will be `'ETIMEDOUT'`. 22 * 23 * @name timeout 24 * @static 25 * @memberOf module:Utils 26 * @method 27 * @category Util 28 * @param {AsyncFunction} asyncFn - The async function to limit in time. 29 * @param {number} milliseconds - The specified time limit. 30 * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) 31 * to timeout Error for more information.. 32 * @returns {AsyncFunction} Returns a wrapped function that can be used with any 33 * of the control flow functions. 34 * Invoke this function with the same parameters as you would `asyncFunc`. 35 * @example 36 * 37 * function myFunction(foo, callback) { 38 * doAsyncTask(foo, function(err, data) { 39 * // handle errors 40 * if (err) return callback(err); 41 * 42 * // do some stuff ... 43 * 44 * // return processed data 45 * return callback(null, data); 46 * }); 47 * } 48 * 49 * var wrapped = async.timeout(myFunction, 1000); 50 * 51 * // call `wrapped` as you would `myFunction` 52 * wrapped({ bar: 'bar' }, function(err, data) { 53 * // if `myFunction` takes < 1000 ms to execute, `err` 54 * // and `data` will have their expected values 55 * 56 * // else `err` will be an Error with the code 'ETIMEDOUT' 57 * }); 58 */ 59 function timeout(asyncFn, milliseconds, info) { 60 var fn = (0, _wrapAsync2.default)(asyncFn); 61 62 return (0, _initialParams2.default)((args, callback) => { 63 var timedOut = false; 64 var timer; 65 66 function timeoutCallback() { 67 var name = asyncFn.name || 'anonymous'; 68 var error = new Error('Callback function "' + name + '" timed out.'); 69 error.code = 'ETIMEDOUT'; 70 if (info) { 71 error.info = info; 72 } 73 timedOut = true; 74 callback(error); 75 } 76 77 args.push((...cbArgs) => { 78 if (!timedOut) { 79 callback(...cbArgs); 80 clearTimeout(timer); 81 } 82 }); 83 84 // setup timer and call original function 85 timer = setTimeout(timeoutCallback, milliseconds); 86 fn(...args); 87 }); 88 } 89 module.exports = exports['default'];