Reputation: 1308
i have a situation where my asynchronus nodejs method from a third party library is taking too long. i want to set a timeout limit on this call and if it does not return within that timeout, i want a callback to happen with default(empty) values.
current code
wrapperfunct(data, function(value, err) {
//do everything with value or err
})
wrapperfunc(data, callback) {
thirdpartylib.getData(input, callback)
}
i am noticing that getData sometimes hangs, that prevents the callback from happening. i want a behavior than if getData does not call the callback method in specified time, i call callback with default values, say (null, null).
Upvotes: 2
Views: 420
Reputation: 707696
You can make your own timeout like this:
wrapperfunc(obj, timeout, data, callback) {
var done = false;
var timer = setTimeout(function() {
done = true;
// callback with both values null to signify a timeout
callback(null, null);
}, timeout);
obj.thirdpartylib.getData(input, function(err, data) {
if (!done) {
clearTimeout(timer);
done = true;
callback(err, data);
}
})
}
Note: The value of this
in your proposed function was probably not correct so I substituted obj
. You will either have to pass that value in or you will have to use some variable that is within scope for that.
Upvotes: 3