手写一个简易的Promise
Promise/A+
手写Promise都是按照 Promise/A+来完成的。每一个步骤都应该和Promise/A+对应起来。
简易版完整代码
class MyPromise {
//私有属性
#status = 'pending'
constructor(fn) {
this.queue = []
const resolve = (data) => {
this.#status = 'fulfilled'
const f1f2 = this.queue.shift()
if (!f1f2 || !f1f2[0]) return
const x = f1f2[0].call(undefined, data)
if (x instanceof Promise2) {
x.then((data) => {
resolve(data)
}, (reason) => {
reject(reason)
})
} else {
resolve(x)
}
}
const reject = (reason) => {
this.#status = 'rejected'
const f1f2 = this.queue.shift()
if (!f1f2 || !f1f2[1]) return
const x = f1f2[1].call(undefined, reason)
if (x instanceof Promise2) {
x.then((data) => {
resolve(data)
}, (reason) => {
reject(reason)
})
} else {
resolve(x)
}
}
fn.call(undefined, resolve, reject)
}
// 链式调用未完成。目前思路是通过状态来分类讨论。
then(f1, f2) {
this.queue.push([f1, f2])
}
}
// 测试代码
const p = new MyPromise(function (resolve, reject) {
setTimeout(function () {
reject('出错')
}, 3000)
})
p.then((data) => { console.log(data) }, (r) => { console.error(r) })