function promiseAS(fn) {
// 0: pending, 1: fulfilled, 2: rejected
this.state = 0
this.value
// 储存resolve函数
this.resFn = []
// 储存reject函数
this.rejFn = []
const resolve = v => {
this.state = 1
this.value = v
this.resFn.forEach(item => {
if (!item) return
item(this.value)
})
}
const reject = v => {
this.state = 2
this.value = v
this.rejFn.forEach(item => {
if (!item) return
item(this.value)
})
}
// 将resolve和reject函数传入fn函数
try {
fn(resolve, reject)
} catch (err) {
reject(err)
}
}
// 原型链继挂载then方法
promiseAS.prototype.then = function (resolve, reject) {
if (this.state === 1) {
resolve(this.value)
}
if (this.state === 2) {
reject(this.value)
}
if (this.state === 0) {
this.resFn.push(resolve)
this.rejFn.push(reject)
}
return this
}
// 原型链继挂载catch方法
promiseAS.prototype.catch = function (reject) {
if (this.state === 2) {
reject(this.value)
}
if (this.state === 0) {
this.rejFn.push(reject)
}
return this
}
// 测试手写的promise
new promiseAS((resolve, reject) => {
setTimeout(() => {
resolve('resolve')
reject('reject')
}, 1000)
})
.then(res => {
console.log(res, 'GuAo')
})
.catch(err => {
console.log(err, 'GuAo')
})
手写promise
最新推荐文章于 2023-05-30 08:44:50 发布