Skip to content

Commit

Permalink
allow fn wrapped in timeout to be called multiple times (fixes #1418)
Browse files Browse the repository at this point in the history
  • Loading branch information
hargasinski committed May 21, 2017
1 parent c1142c7 commit 4f6ece1
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 21 deletions.
41 changes: 20 additions & 21 deletions lib/timeout.js
Expand Up @@ -43,33 +43,32 @@ import wrapAsync from './internal/wrapAsync';
* });
*/
export default function timeout(asyncFn, milliseconds, info) {
var originalCallback, timer;
var timedOut = false;
var fn = wrapAsync(asyncFn);

function injectedCallback() {
if (!timedOut) {
originalCallback.apply(null, arguments);
clearTimeout(timer);
}
}
return initialParams(function (args, callback) {
var timedOut = false;
var timer;

function timeoutCallback() {
var name = asyncFn.name || 'anonymous';
var error = new Error('Callback function "' + name + '" timed out.');
error.code = 'ETIMEDOUT';
if (info) {
error.info = info;
function timeoutCallback() {
var name = asyncFn.name || 'anonymous';
var error = new Error('Callback function "' + name + '" timed out.');
error.code = 'ETIMEDOUT';
if (info) {
error.info = info;
}
timedOut = true;
callback(error);
}
timedOut = true;
originalCallback(error);
}

var fn = wrapAsync(asyncFn);
args.push(function () {
if (!timedOut) {
callback.apply(null, arguments);
clearTimeout(timer);
}
});

return initialParams(function (args, origCallback) {
originalCallback = origCallback;
// setup timer and call original function
timer = setTimeout(timeoutCallback, milliseconds);
fn.apply(null, args.concat(injectedCallback));
fn.apply(null, args);
});
}
36 changes: 36 additions & 0 deletions mocha_test/timeout.js
Expand Up @@ -69,4 +69,40 @@ describe('timeout', function () {
done();
});
});

it('timeout with multiple calls (#1418)', function(done) {
var timeout = async.timeout(function asyncFn(n, callback) {
if (n < 1) {
setTimeout(function() {
callback(null, 'I will time out');
}, 75);
} else {
async.setImmediate(function() {
callback(null, 'I didn\'t time out');
})
}
}, 50);

async.series([
function(cb) {
timeout(0, function(err, result) {
expect(err.message).to.equal('Callback function "asyncFn" timed out.');
expect(err.code).to.equal('ETIMEDOUT');
expect(err.info).to.equal(undefined);
expect(result).to.equal(undefined);
cb();
});
},
function(cb) {
timeout(1, function(err, result) {
expect(err).to.equal(null);
expect(result).to.equal('I didn\'t time out');
cb();
});
}
], function(err) {
expect(err).to.equal(null);
done();
});
})
});

0 comments on commit 4f6ece1

Please sign in to comment.