Created
June 18, 2014 14:48
-
-
Save bahmutov/9651f99760cd5cee22c1 to your computer and use it in GitHub Desktop.
Add q-timeout to promises with either a value or callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.