Skip to content

Commit

Permalink
Exceptions in when callbacks are transformed into rejections.
Browse files Browse the repository at this point in the history
  • Loading branch information
kriskowal committed Feb 1, 2011
1 parent 9c4f14a commit b0ebd9a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
5 changes: 5 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ Deprecations:
Mark Miller in a style where TitleCase is reserved for
constructors.

Next minor release
- Exceptions thrown in the callbacks of a `when` call
are now consumed, warned, and transformed into
rejections of the promise returned by `when`.

0.2.7
- Fixed a minor bug in thenable assimilation, regressed
because of the change in the forwarding protocol.
Expand Down
27 changes: 25 additions & 2 deletions lib/q.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ var create = Object.create || function create(prototype) {
return new Type();
}

var print = typeof console === "undefined" ? identity : function (message) {
console.log(message);
};

/**
* Performs a task in a future turn of the event loop.
* @param {Function} task
Expand Down Expand Up @@ -355,16 +359,35 @@ function when(value, resolved, rejected) {
var deferred = defer();
var done = false; // ensure the untrusted promise makes at most a
// single call to one of the callbacks

function _resolved(value) {
try {
return resolved ? resolved(value) : value;
} catch (exception) {
print(exception && exception.stack || exception);
return reject(exception);
}
}

function _rejected(reason) {
try {
return rejected ? rejected(reason) : reject(reason);
} catch (exception) {
print(exception && exception.stack || exception);
return reject(exception);
}
}

forward(ref(value), "when", function (value) {
if (done)
return;
done = true;
deferred.resolve(ref(value)[DUCK]("when", resolved, rejected));
deferred.resolve(ref(value)[DUCK]("when", _resolved, _rejected));
}, function (reason) {
if (done)
return;
done = true;
deferred.resolve(rejected ? rejected(reason) : reject(reason));
deferred.resolve(_rejected(reason));
});
return deferred.promise;
}
Expand Down

0 comments on commit b0ebd9a

Please sign in to comment.