3 Object.defineProperty(exports, "__esModule", {
6 exports.default = timeout;
8 var _initialParams = require('./internal/initialParams');
10 var _initialParams2 = _interopRequireDefault(_initialParams);
12 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15 * Sets a time limit on an asynchronous function. If the function does not call
16 * its callback within the specified milliseconds, it will be called with a
17 * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
21 * @memberOf module:Utils
24 * @param {Function} asyncFn - The asynchronous function you want to set the
26 * @param {number} milliseconds - The specified time limit.
27 * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
28 * to timeout Error for more information..
29 * @returns {Function} Returns a wrapped function that can be used with any of
30 * the control flow functions. Invoke this function with the same
31 * parameters as you would `asyncFunc`.
34 * function myFunction(foo, callback) {
35 * doAsyncTask(foo, function(err, data) {
37 * if (err) return callback(err);
39 * // do some stuff ...
41 * // return processed data
42 * return callback(null, data);
46 * var wrapped = async.timeout(myFunction, 1000);
48 * // call `wrapped` as you would `myFunction`
49 * wrapped({ bar: 'bar' }, function(err, data) {
50 * // if `myFunction` takes < 1000 ms to execute, `err`
51 * // and `data` will have their expected values
53 * // else `err` will be an Error with the code 'ETIMEDOUT'
56 function timeout(asyncFn, milliseconds, info) {
57 var originalCallback, timer;
60 function injectedCallback() {
62 originalCallback.apply(null, arguments);
67 function timeoutCallback() {
68 var name = asyncFn.name || 'anonymous';
69 var error = new Error('Callback function "' + name + '" timed out.');
70 error.code = 'ETIMEDOUT';
75 originalCallback(error);
78 return (0, _initialParams2.default)(function (args, origCallback) {
79 originalCallback = origCallback;
80 // setup timer and call original function
81 timer = setTimeout(timeoutCallback, milliseconds);
82 asyncFn.apply(null, args.concat(injectedCallback));
85 module.exports = exports['default'];