cancel.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. module.exports = function(Promise) {
  3. var errors = require("./errors.js");
  4. var async = require("./async.js");
  5. var CancellationError = errors.CancellationError;
  6. Promise.prototype._cancel = function (reason) {
  7. if (!this.isCancellable()) return this;
  8. var parent;
  9. var promiseToReject = this;
  10. while ((parent = promiseToReject._cancellationParent) !== undefined &&
  11. parent.isCancellable()) {
  12. promiseToReject = parent;
  13. }
  14. this._unsetCancellable();
  15. promiseToReject._target()._rejectCallback(reason, false, true);
  16. };
  17. Promise.prototype.cancel = function (reason) {
  18. if (!this.isCancellable()) return this;
  19. if (reason === undefined) reason = new CancellationError();
  20. async.invokeLater(this._cancel, this, reason);
  21. return this;
  22. };
  23. Promise.prototype.cancellable = function () {
  24. if (this._cancellable()) return this;
  25. async.enableTrampoline();
  26. this._setCancellable();
  27. this._cancellationParent = undefined;
  28. return this;
  29. };
  30. Promise.prototype.uncancellable = function () {
  31. var ret = this.then();
  32. ret._unsetCancellable();
  33. return ret;
  34. };
  35. Promise.prototype.fork = function (didFulfill, didReject, didProgress) {
  36. var ret = this._then(didFulfill, didReject, didProgress,
  37. undefined, undefined);
  38. ret._setCancellable();
  39. ret._cancellationParent = undefined;
  40. return ret;
  41. };
  42. };