class MyPromise {
constructor(executor) {
this.state = 'pending' //初始化state为等待状态
this.value = undefined // 记录成功的值,将来给.then使用
this.reason = undefined // 记录失败的值,将来给.catch使用
this.onResolvedCallbacks = [] // 存放当成功时,需要执行的函数列表
this.onRejectedCallbacks = [] // 存放当失败时,需要执行的函数列表
let resolve = (value) => {
if (this.state === 'pending') { // 为了实现状态凝固,所以加了个判断
this.state = 'fulfilled' // 更新状态
this.value = value // 记录信息
// 调用成功数组的函数
this.onResolvedCallbacks.forEach(fn => fn())
}
}
let reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected' // 更新状态
this.reason = reason // 记录失败的信息
// 调用失败数组的函数
this.onRejectedCallbacks.forEach(fn => fn())
}
}
// 如果执行executor报错,直接reject
try {
executor(resolve, reject)
} catch (err) {
reject()
}
}
//p.then(onFulFilled,onRejected)
// onFulFilled =>成功后,调用的回调,onRejected =>失败后,调用的回调
then(onFulFilled, onRejected) { //给原型上加.then方法
// 当状态为pending的时候,把要执行的函数先存起来
if (this.state === 'pending') {
// 将成功时候要干的事情,存起来
this.onResolvedCallbacks.push(() => onFulFilled(this.value))
// 将失败的时候要干的事情,存起来
this.onRejectedCallbacks.push(() => onRejected(this.value))
}
}
}
// promiseA+当中,定义传进去的这个回调()=>,叫executor
const p = new MyPromise((resolve, reject) => {
// 这里面的代码是立刻执行的
setTimeout(() => {
resolve(500)
}, 100)
})
// 这里的回调,希望在promise的状态更新后
p.then(res => {
console.log(res)
})
手写一个简单的Promise(不包括链式.then)
于 2023-09-23 23:01:58 首次发布