k8w-super-promise
Version:
Promise with cancel and always
72 lines (67 loc) • 2.16 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
require('core-js/es/promise/finally');
/**
* @author k8w
* email: me@k8w.io
*/
var SuperPromise = /** @class */ (function () {
function SuperPromise(executor) {
var _this = this;
this[Symbol.toStringTag] = 'SuperPromise';
/** have been rs or rj */
this.isCompleted = false;
this.isAborted = false;
this._promise = new Promise(function (rs, rj) {
//重新定义resolve
var newRs = function (value) {
if (_this.isAborted) {
return;
}
_this.isCompleted = true;
rs(value);
};
//重新定义reject
var newRj = function (err) {
if (_this.isAborted) {
return;
}
_this.isCompleted = true;
rj(err);
};
executor(newRs, newRj);
});
}
/**
* 立即取消该Promise
* 如果取消成功或之前已经取消,则返回true
* 如果取消失败(已经resolve或reject),则返回false
*/
SuperPromise.prototype.abort = function () {
var _a;
if (this.isCompleted) {
return false;
}
if (this.isAborted) {
return true;
}
//abort handler
this.isAborted = true;
(_a = this.onAbort) === null || _a === void 0 ? void 0 : _a.call(this);
return true;
};
SuperPromise.prototype.then = function (onfulfilled, onrejected) {
this._promise = this._promise.then(onfulfilled, onrejected);
return this;
};
SuperPromise.prototype["catch"] = function (onrejected) {
this._promise = this._promise["catch"](onrejected);
return this;
};
SuperPromise.prototype["finally"] = function (onfinally) {
this._promise = this._promise["finally"](onfinally);
return this;
};
return SuperPromise;
}());
exports.SuperPromise = SuperPromise;