k8w-super-promise
Version:
Promise with cancel and always
66 lines (63 loc) • 1.8 kB
JavaScript
import 'core-js/es/promise/finally';
/**
* @author k8w
* email: me@k8w.io
*/
class SuperPromise {
constructor(executor) {
this[Symbol.toStringTag] = 'SuperPromise';
/** have been rs or rj */
this.isCompleted = false;
this.isAborted = false;
this._promise = new Promise((rs, rj) => {
//重新定义resolve
let newRs = (value) => {
if (this.isAborted) {
return;
}
this.isCompleted = true;
rs(value);
};
//重新定义reject
let newRj = (err) => {
if (this.isAborted) {
return;
}
this.isCompleted = true;
rj(err);
};
executor(newRs, newRj);
});
}
/**
* 立即取消该Promise
* 如果取消成功或之前已经取消,则返回true
* 如果取消失败(已经resolve或reject),则返回false
*/
abort() {
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;
}
then(onfulfilled, onrejected) {
this._promise = this._promise.then(onfulfilled, onrejected);
return this;
}
catch(onrejected) {
this._promise = this._promise.catch(onrejected);
return this;
}
finally(onfinally) {
this._promise = this._promise.finally(onfinally);
return this;
}
}
export { SuperPromise };