Skip to content

Instantly share code, notes, and snippets.

@bahmutov
Created June 18, 2014 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahmutov/9651f99760cd5cee22c1 to your computer and use it in GitHub Desktop.
Save bahmutov/9651f99760cd5cee22c1 to your computer and use it in GitHub Desktop.
Add q-timeout to promises with either a value or callback
/**
Example: timeout with message, just like Q.promise.timeout
foo()
.timeout(500, 'promise timed out!')
.then(function () {
console.log('foo has been resolved!');
})
.fail(function (msg) {
console.log('failed with value:', msg);
});
Example: timeout with callback, reject deferred if you want
foo()
.timeout(500, function (defer) {
console.log('timed out callback');
defer.reject();
})
.fail(function (msg) {
if (msg)
console.log('failed with value:', msg);
});
*/
var installed = false;
module.exports = function (q) {
(function addPromiseTimeoutSupport(q) {
if (installed) {
return;
}
var _defer = q.defer;
q.defer = function () {
var d = _defer();
d.promise.timeout = function (ms, timedOutValue) {
setTimeout(function () {
if (typeof timedOutValue === 'function') {
timedOutValue(d);
} else {
d.reject(timedOutValue);
}
}, ms);
return d.promise;
};
return d;
};
installed = true;
}(q));
};
@bahmutov
Copy link
Author

I always wanted to run a callback on promise timeout. Q.promise.timeout is almost what I needed, this adds ability to run a dedicated callback. One still needs to detect if the promise was rejected due to timeout in .fail callback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment