Skip to content

Instantly share code, notes, and snippets.

@azu
Created May 3, 2014 09:26
Show Gist options
  • Save azu/11494644 to your computer and use it in GitHub Desktop.
Save azu/11494644 to your computer and use it in GitHub Desktop.
cancellable promise top on `Promise` @ https://github.com/azu/promises-book/issues/6
/**
* Created by azu on 2014/05/02.
* LICENSE : MIT
*/
"use strict";
var CancellablePromise = require("../src/cancellable-promise");
describe("CancellablePromise", function () {
it("is cancellable promise", function (done) {
var promise = new CancellablePromise(function (resolve, reject) {
setTimeout(function () {
reject(new Error("reason is reasonable"));
}, 1000);
});
promise.onCancel(function (reason) {
console.log("2. main canceled", reason);
done();
});
var result = promise.then(function (value) {
console.log(value);
}).catch(function (error) {
console.error("-", error);
done();
});
result.onCancel(function () {
console.log("1. result canceled");
});
result.cancel("Da!");
});
});
/**
* Created by azu on 2014/05/02.
* LICENSE : MIT
*/
"use strict";
var CancellablePromise = function (executor) {
this._canceld = false;
Promise.call(this, executor);
};
if (typeof Object.setPrototypeOf === "function") {
Object.setPrototypeOf(CancellablePromise, Promise);
} else {
CancellablePromise.__proto__ = Promise;
}
CancellablePromise.prototype = Object.create(Promise.prototype, {
constructor: {
value: CancellablePromise
}
});
CancellablePromise.prototype.cancel = function (reason) {
var targetPromise = this;
do {
targetPromise._canceld = true;
if (targetPromise._callback) {
targetPromise._callback.call(targetPromise, reason);
}
} while (targetPromise = targetPromise._parentPromise);
};
CancellablePromise.prototype.isCanceled = function () {
return this._canceld;
};
CancellablePromise.prototype.onCancel = function (fn) {
this._callback = fn;
};
CancellablePromise.prototype.then = function passCatch(onFulfilled, onRejected) {
var that = this;
var promise = Promise.prototype.then.call(that, function (value) {
if (!that.isCanceled()) {
onFulfilled.call(that, value);
}
}, function (reason) {
if (!that.isCanceled()) {
onRejected.call(that, reason);
}
});
promise._parentPromise = this;
return promise;
};
module.exports = CancellablePromise;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment