console.log(res)
return 2
},
err => {}
)
.then(
res => {
console.log(res)
},
err => {}
)
我们首先要实现一个 Promise 的类,这个类的构造函数会传入一个函数作为参数,并且向该函数传入 resolve 和 reject 两个方法。
初始化 Promise 的状态为 pending。
class MyPromise {
constructor(executor) {
this.executor = executor
this.value = null
this.status = ‘pending’
const resolve = value => {
if (this.status === ‘pending’) {
this.value = value // 调用 resolve 后记录 resolve 的值
this.status = ‘fulfilled’ // 调用 resolve 扭转 promise 状态
}
}
const reject = value => {
if (this.status === ‘pending’) {
this.value = value // 调用 reject 后记录 reject 的值
this.status = ‘rejected’ // 调用 reject 扭转 promise 状态
}
}
this.executor(resolve, reject)
}
(2)接下来要实现 promise 对象上的 then 方法,then 方法会传入两个函数作为参数,分别作为 promise 对象 resolve 和 reject 的处理函数。
这里要注意三点:
- then 函数需要返回一个新的 promise 对象
- 执行 then 函数的时候这个 promise 的状态可能还没有被扭转为 fulfilled 或 rejected
- 一个 promise 对象可以同时多次调用 then 函数
class MyPromise {
constructor(executor) {
this.executor = executor
this.value = null
this.status = ‘pending’
this.onFulfilledFunctions = [] // 存放这个 promise 注册的 then 函数中传的第一个函数参数
this.onRejectedFunctions = [] // 存放这个 promise 注册的 then 函数中传的第二个函数参数
const resolve = value => {
if (this.status === ‘pending’) {
this.value = value
this.status = ‘fulfilled’
this.onFulfilledFunctions.forEach(onFulfilled => {
onFulfilled() // 将 onFulfilledFunctions 中的函数拿出来执行
})
}
}
const reject = value => {
if (this.status === ‘pending’) {
this.value = value
this.status = ‘rejected’
this.onRejectedFunctions.forEach(onRejected => {
onRejected() // 将 onRejectedFunctions 中的函