function MyPromise(excutor) {
// 内部状态,默认为pending
this.state = 'Pending';
this.resolveFuncCallbacks = [];
this.rejctedFuncCallbacks = [];
const self = this;
// 内部提供改变状态的函数
function resovle() {
// 状态只能修改一次,多次修改无效
if (self.state === 'pending') {
self.state = 'fullfied';
self.resolveFuncCallbacks.forEach(item => item(self.value));
}
}
// 内部提供改变状态的函数
function reject() {
// 状态只能修改一次,多次修改无效
if (self.state === 'pending') {
self.state = 'rejected';
self.rejctedFuncCallbacks.forEach(item => item(self.reason));
}
}
// 构造函数是立即执行的
try {
excutor(resovle, reject);
} catch (e) {
console.log(e);
}
}
/**
* @desc MyPromise.then返回的任然是一个Promise
*/
MyPromise.prototype.then = function (resovleFunc, rejctedFunc) {
// then的构造函数参数可能不是函数,转成函数
resovleFunc = typeof resovleFunc === 'function' ? resovleFunc : (resovleFunc) => resovleFunc;
rejctedFunc = typeof rejctedFunc === 'function' ? resovleFunc : (rejctedFunc) => rejctedFunc;
const self = this;
return new MyPromise((resolve, reject) => {
console.log('MyPromise', 2222);
// 还需要看一下上一次 .then 的返回值是不是 MyPormise的实例
// 需要把 onFulfilled onRejected这两个函数包装一下如果返回结果是任然是个Promise,则把下一个.then的回调传进去
const decorateResolveFunc = function(value) {
const result = resovleFunc(value);
return result instanceof MyPromise ? result.then(resolve, reject) : result;
}
const decorateRejectFunc = function(reason) {
const result = rejctedFunc(reason);
return result instanceof MyPromise ? result.then(resolve, reject) : result;
}
// then 函数并不是马上就执行的,如果是pending状态的话,就先攒起来
if (self.state === 'pending') {
self.resolveFuncCallbacks.push(decorateResolveFunc);
self.rejctedFuncCallbacks.push(decorateRejectFunc);
}
// 如果是 fullfiled 状态直接执行成功的回调
if (self.state === 'fullfied') {
decorateResolveFunc(self.value);
}
// 如果是 rejected 状态直接执行失败的回调
if (self.state) {
decorateRejectFunc(self.reason);
}
})
}
// 先写点用例
const p1 = new MyPromise((resolve, reject) => {
resovle('33');
})
p1.then((val) => {
console.log('then', val);
return val;
}, (reason) => {
console.log('then', reason);
return reason;
}).then(res => console.log('then, then', res))
console