class MyPromise2 {
constructor(executor) {
this.state = "pending"
this.value = undefined
this.reason = undefined
this.successCB = []
this.failCB = []
let resolve = (value) => {
if(this.state === "pending") {
this.state = "fulfilled"
this.value = value
this.successCB.forEach(f => f())
}
}
let reject = (reason) => {
if(this.state === "pending") {
this.state = "rejected"
this.value = value
this.failCB.forEach(f => f())
}
}
try {
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
then(onFulfillled, onRejected) {
if(this.state === "fulfilled") {
onFulfillled(this.value)
}
if(this.state === "rejected") {
onRejected(this.value)
}
if(this.state === "pending") {
this.successCB.push(()=>{
onRejected(this.value)
})
this.failCB.push(()=> {
onRejected(this.reason)
})
}
}
}
Promise.all = function(promises) {
let list = []
let count = 0
function handle(i, data) {
list[i] = data
count++
if(count = promises.length) {
resolve(list)
}
}
return Promise((resolve, reject) =>{
for(let i = 0; i < promises.length; i++) {
promises[i].then(res=>{
handle(i, res)
}, err => reject(err))
}
})
}
JS Promise原理
最新推荐文章于 2024-04-09 18:47:28 发布