new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve("失败");
}, 3000);
}).then((value) => {
console.log("回调" + value);
}).catch((value) => {
console.log("回调" + value);
})
- 从使用出发
- 三状态:等待、接受、拒绝,状态不可逆
- 立即执行函数 exector
- 链式传入回调
function MyPromise(exector) {
this.status = "pending";
this.data = null;
this.onResolve = [];
this.onReject = [];
exector(this.resolve.bind(this), this.reject.bind(this));
}
MyPromise.prototype.resolve = function (value) {
if (this.status === "pending") {
this.status = "resolved";
this.data = value;
for (var i = 0; i < this.onResolve.length; i++) {
this.onResolve[i](value);
}
}
};
MyPromise.prototype.reject = function (value) {
if (this.status === "pending") {
this.status = "rejected";
this.data = value;
for (var i = 0; i < this.onReject.length; i++) {
this.onReject[i](value);
}
}
};
MyPromise.prototype.then = function (func) {
this.onResolve.push(func);
return this
};
MyPromise.prototype.catch = function (func) {
this.onReject.push(func);
return this
};