Skip to content

Commit

Permalink
Catch errors that are thrown in the abort handler
Browse files Browse the repository at this point in the history
  • Loading branch information
mjackson committed Aug 18, 2014
1 parent 1454211 commit 4cc0372
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions modules/utils/AbortablePromise.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
var Promise = require('bluebird').Promise;

function makeAbortable(promise, abortHandler) {
promise.abort = abortHandler;
function makeAbortable(promise, onAbort) {
promise.abort = onAbort;

// Hijack promise.then so it returns an abortable promise.
var _then = promise.then;
promise.then = function () {
return makeAbortable(_then.apply(promise, arguments), abortHandler);
return makeAbortable(_then.apply(promise, arguments), onAbort);
};

return promise;
Expand Down Expand Up @@ -43,7 +43,7 @@ function AbortablePromise(resolver) {
if (typeof resolver !== 'function')
throw new Error('AbortablePromise needs a resolver function');

var abortHandler;
var abortHandler, onAbort;
var promise = new Promise(function (resolve, reject) {
resolver(function () {
abortHandler = null;
Expand All @@ -57,16 +57,23 @@ function AbortablePromise(resolver) {

abortHandler = handler;
});
});

return makeAbortable(promise, function () {
if (abortHandler != null) {
onAbort = function () {
if (abortHandler == null)
return;

var handler = abortHandler;
abortHandler = null;

return handler.apply(this, arguments);
}
try {
return handler.apply(this, arguments);
} catch (error) {
reject(error);
}
};
});

return makeAbortable(promise, onAbort);
}

module.exports = AbortablePromise;

0 comments on commit 4cc0372

Please sign in to comment.