function MyPromise(f){
this.status = 'pending'
this.value = ''
this.reason = ''
this.onResolveCB = []
this.onRejectCB = []
this.then = (onFulfilled, onRejected) => {
if (this.status === 'fulfilled') {
onFulfilled(this.value)
}
if (this.status === 'rejected') {
onRejected(this.reason)
}
if (this.status === 'pending') {
// 如果promise的状态是 pending,需要将 onFulfilled 和 onRejected 函数存放起来,等待状态确定后,再依次将对应的函数执行
this.onResolveCB.push(() => {
onFulfilled(this.value)
});
// 如果promise的状态是 pending,需要将 onFulfilled 和 onRejected 函数存放起来,等待状态确定后,再依次将对应的函数执行
this.onRejectCB.push(()=> {
onRejected(this.reason);
})
}
}
this.resolve = (val) => {
if(this.status === 'pending'){
this.status = 'fulfilled'
this.value = val
this.onResolveCB.forEach(fn => fn())
}
}
this.reject = (err) => {
if(this.status === 'pending'){
this.status = 'rejected'
this.reason = err
this.onRejectCB.forEach(fn => fn())
}
}
try{
f(this.resolve,this.reject)
}catch(err){
console.log(err)
}
}
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功');
},1000);
}).then(
(data) => {
console.log('success', data)
},
(err) => {
console.log('faild', err)
}
)
//无链式调用
console