Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Allow when/delay to be externally resolved #52

Closed
wants to merge 1 commit into from

2 participants

Scott Andrews Brian Cavalier
Scott Andrews
Collaborator
  • returns a full deferred instead of a promise
  • clears the timeout when resolved/rejected
Scott Andrews scothis Allow when/delay to be externally resolved
- returns a full deferred instead of a promise
- clears the timeout when resolved/rejected
8d17d48
Brian Cavalier

The reject case is easy to achieve without adding any new functionality. The ability to short-circuit the delay by fulfilling is a bit trickier. It seems doable via any or race tho:

var p = when.promise(function(resolve, reject) {
    // control the promise's fate however you need
});
return when.race([p, when(x).delay(1000)]);

If p fulfills or rejects in < 1 second, it wins. Otherwise, delayed x wins.

How or where would you ever use this construct, tho? If there's no common use cases, and it's achievable using race, I think we should close this.

Brian Cavalier

Gonna close this for now. If there's a strong need to be able to do it, I think we should add that to the reasons to make when.race public.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Aug 30, 2012
  1. Scott Andrews

    Allow when/delay to be externally resolved

    scothis authored
    - returns a full deferred instead of a promise
    - clears the timeout when resolved/rejected
This page is out of date. Refresh to see the latest.
Showing with 22 additions and 4 deletions.
  1. +10 −4 delay.js
  2. +12 −0 test/delay.js
14 delay.js
View
@@ -16,7 +16,7 @@ define(['./when'], function(when) {
var undef;
/**
- * Creates a new promise that will resolve after a msec delay. If promise
+ * Creates a new deferred that will resolve after a msec delay. If promise
* is supplied, the delay will start *after* the supplied promise is resolved.
*
* Usage:
@@ -39,13 +39,19 @@ define(['./when'], function(when) {
promise = undef;
}
- var deferred = when.defer();
+ var deferred, timeout;
- setTimeout(function() {
+ deferred = when.defer();
+ timeout = setTimeout(function() {
deferred.resolve(promise);
}, msec);
- return deferred.promise;
+ deferred.promise.always(function () {
+ clearTimeout(timeout);
+ timeout = undef;
+ });
+
+ return deferred;
};
});
12 test/delay.js
View
@@ -59,6 +59,18 @@ buster.testCase('when/delay', {
assert.equals(val, 1);
}
).always(done);
+ },
+
+ 'should clear timeout on reject': function(done) {
+ var d = delay(0);
+ d.reject(1);
+
+ d.then(
+ fail,
+ function(val) {
+ assert.equals(val, 1);
+ }
+ ).always(done);
}
});
})(
Something went wrong with that request. Please try again.