想起刚学promise时,对他迷茫了很久,后来了解Eventloop,才真正知悉他的流程。
现把之前封装的贡献一下。
class myPromise {
constructor(fn) {
//初始化各个状态
this.state = 'pending'
this.value = null
this.fulfilledCallBack = []
this.rejectedCallback = []
//resolve函数的实现
let resolve = (value) => {
if (this.state == 'pending') {
this.state = 'fulfilled'
this.value = value
this.fulfilledCallBack.map((cb) => cb(this.value)) 遍历执行异步队列的事件
}
}
//reject 函数的实现(同理)
let reject = (value) => {
if (this.state == 'pending') {
this.state = 'rejected'
this.value = value
this.rejectedCallBack.map((cb) => cb(this.value))
}
}
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}
}
then(onFulfilled, onRejected) {
onFulfilled ? onFulfilled : (e) => e
onRejected ? onRejected : (e) => e
switch (this.state) {
case 'fulfilled':
onFulfilled(this.value)
break;
case 'rejected':
onRejected(this.value)
break;
//遇到异步事件时还是pending状态,扔到对应队列中。
case 'pending':
this.fulfilledCallBack.push(onFulfilled)
this.rejectedCallBack.push(onRejected)
break;
}
}
all(promiseArr) { //简易版的all
return new myPromise((res, rej) => {
let times = 0
let resolveArr = []
for (let i = 0; i < promiseArr.length; i++) {
promiseArr.then((val) => {
resolveArr.push(val)
times++
if (times == promiseArr.length)
res(resolveArr)
}, (rea) => {
rej(rea)
})
}
})
}
}