Permalink
Browse files

added; .end()

  • Loading branch information...
aheckmann committed Jan 9, 2013
1 parent c9e1e54 commit f8479bab27179ed373308156a0b1747643f6bca1
Showing with 49 additions and 1 deletion.
  1. +28 −1 lib/promise.js
  2. +21 −0 test/promise.test.js
View
@@ -20,6 +20,7 @@ var EventEmitter = require('events').EventEmitter;
function Promise (back) {
this.emitted = {};
+ this.ended = false;
if ('function' == typeof back)
this.onResolve(back);
}
@@ -152,7 +153,6 @@ Promise.prototype.onReject = function (fn) {
*/
Promise.prototype.onResolve = function (fn) {
- // TODO maybe refactor out this wrapped fn?
this.on(this.constructor.FAILURE, function(err){
fn.call(this, err);
});
@@ -202,6 +202,7 @@ Promise.prototype.then = function (onFulfill, onReject) {
try {
val = fn(arg);
} catch (err) {
+ if (retPromise.ended) throw err;
return retPromise.reject(err);
}
@@ -232,6 +233,32 @@ Promise.prototype.then = function (onFulfill, onReject) {
return retPromise;
}
+/**
+ * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught.
+ *
+ * ####Example:
+ *
+ * var p = new Promise;
+ * p.then(function(){ throw new Error('shucks') });
+ * setTimeout(function () {
+ * p.fulfill();
+ * // error was caught and swallowed by the promise returned from
+ * // p.then(). we either have to always register handlers on
+ * // the returned promises or we can do the following...
+ * }, 10);
+ *
+ * // this time we use .end() which prevents catching thrown errors
+ * var p = new Promise;
+ * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <--
+ * setTimeout(function () {
+ * p.fulfill(); // throws "shucks"
+ * }, 10);
+ */
+
+Promise.prototype.end = function () {
+ this.ended = true;
+}
+
/*!
* Module exports.
*/
View
@@ -176,5 +176,26 @@ describe('promise', function(){
}, 10);
})
+
+ it('can be disabled using .end()', function(done){
+ var p = new Promise;
+
+ var p2 = p.then(function () { throw new Error('shucks') })
+ p2.end();
+
+ setTimeout(function () {
+ try {
+ p.fulfill();
+ } catch (err) {
+ assert.ok(/shucks/.test(err))
+ done();
+ }
+
+ setTimeout(function () {
+ done(new Error('error was swallowed'));
+ }, 10);
+
+ }, 10);
+ })
})
})

0 comments on commit f8479ba

Please sign in to comment.