One problem with using an "external" timeout for the promise is that you 
(potentially) waste resources. Promises can't be cancelled (yet?) which 
means that even thought you'll never look at the result, node will still 
continue to generate the value and take up the same resources doing it, 
both in your app and potentially on upstream systems. It's often a good 
idea to push the timeout up to the code that actually knows how to 
abort/cancel. E.g. adding good timeout logic to your http client or 
database library (or whatever the thing is you want to time out) which can 
reject the innermost promise and immediately close the resources.

On Thursday, June 25, 2015 at 11:09:40 AM UTC-7, al...@vidao.com wrote:
>
> Hello,
>
> Being relatively new to promises, a few months into using them (the native 
> implementation on nodejs) I found myself adding timeout rejections 
> repeatedly. For me it is a very common use case.
>
> I took a quick look and didn't find Promises with built in timeouts. The 
> code below is my wrapper to handle that, it seems to work fine & passes my 
> tests. The 2 questions I have are (1) is there something that's commonly 
> used for this that I missed in my search and (2) if not - does the wrapper 
> seem alright or is there a potential problem?
>
> Thank you!
> Alen
>
> var DEFAULT_TIMEOUT = 5000;
>
> var TimedPromise = function(timeoutAfter) {
>
> var _self = this;
>
> var _rejectFunc;
> var _resolveFunc;
>
> var _timeoutMs = timeoutAfter ? timeoutAfter : DEFAULT_TIMEOUT;
>
> var _promise = new Promise(function(resolveFunc, rejectFunc) {
> _resolveFunc = resolveFunc.bind(this);
> _rejectFunc = rejectFunc.bind(this);
> });
>
> var _timeout = setTimeout(function() {
>
> if (_rejectFunc) {
> _rejectFunc(Error('timeout'));
> }
> else {
>
> _promise.then = function() {
> return Promise.reject(new Error('timeout'));
> };
> }
> },
> _timeoutMs
> );
>
> _self.resolve = function(arg) {
>
> if (_timeout) {
> clearTimeout(_timeout);
> }
>
> _resolveFunc(arg);
> };
>
> _self.reject = function(arg) {
>
> if (_timeout) {
> clearTimeout(_timeout);
> }
>
> _rejectFunc(arg);
> };
>
> _self.promise = function() {
> return _promise;
> };
>
> };
>
> exports = module.exports = TimedPromise;
>
>
>
>

-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to nodejs+unsubscr...@googlegroups.com.
To post to this group, send email to nodejs@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/6fe3df2a-a307-448f-8f90-153be9e06d59%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to