Browse Source

Implemented Promise.timeout() and Promise.cancel()

v0.7.4-release
Felix Geisendörfer 15 years ago
committed by Ryan Dahl
parent
commit
0dbf2d7792
  1. 40
      src/events.js
  2. 27
      test/mjsunit/test-promise-cancel.js
  3. 34
      test/mjsunit/test-promise-timeout.js

40
src/events.js

@ -21,6 +21,41 @@ node.EventEmitter.prototype.listeners = function (type) {
};
// node.Promise is defined in src/events.cc
node.Promise.prototype.cancel = function() {
this._events['success'] = [];
this._events['error'] = [];
this.emitSuccess = function() {};
this.emitError = function() {};
this.emitCancel();
};
node.Promise.prototype.emitCancel = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift('cancel');
this.emit.apply(this, args);
};
node.Promise.prototype.timeout = function(timeout) {
if (timeout === undefined) {
return this._timeoutDuration;
}
this._timeoutDuration = timeout;
if (this._timer) {
clearTimeout(this._timer);
}
var self = this
this._timer = setTimeout(function() {
self.emitError(new Error('timeout'));
self.cancel();
}, this._timeoutDuration);
return this;
};
node.Promise.prototype.addCallback = function (listener) {
this.addListener("success", listener);
@ -32,6 +67,11 @@ node.Promise.prototype.addErrback = function (listener) {
return this;
};
node.Promise.prototype.addCancelback = function (listener) {
this.addListener("cancel", listener);
return this;
};
node.Promise.prototype.wait = function () {
var ret;
var had_error = false;

27
test/mjsunit/test-promise-cancel.js

@ -0,0 +1,27 @@
node.mixin(require("common.js"));
var cancelFired = false;
var promise = new node.Promise();
promise.addCallback(function() {
assertUnreachable('addCallback should not fire after promise.cancel()');
});
promise.addErrback(function() {
assertUnreachable('addErrback should not fire after promise.cancel()');
});
promise.addCancelback(function() {
cancelFired = true;
});
promise.cancel();
setTimeout(function() {
promise.emitSuccess();
promise.emitError();
}, 100);
process.addListener('exit', function() {
assertTrue(cancelFired);
});

34
test/mjsunit/test-promise-timeout.js

@ -0,0 +1,34 @@
node.mixin(require("common.js"));
var timeouts = 0;
var promise = new node.Promise();
promise.timeout(250);
assertEquals(250, promise.timeout());
promise.addCallback(function() {
assertUnreachable('addCallback should not fire after a promise error');
});
promise.addErrback(function(e) {
assertInstanceof(e, Error);
assertEquals('timeout', e.message);
timeouts++;
});
setTimeout(function() {
promise.emitSuccess('Am I too late?');
}, 500);
var waitPromise = new node.Promise();
try {
waitPromise.timeout(250).wait()
} catch (e) {
assertInstanceof(e, Error);
assertEquals('timeout', e.message);
timeouts++;
}
process.addListener('exit', function() {
assertEquals(2, timeouts);
});
Loading…
Cancel
Save