文章目录
1.实现一个简单的 promise
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 1000);
}).then(res => {
console.log(res);
return 2;
}, err = {
}).then(res => {
console.log(res);
}, err => {
});
为了实现上述功能,从构造函数的角度,我们首先要实现一个 Promise 的类,这个类的构造函数会传入一个函数作为参数,并且向该函数传入 resolve 和 reject 两个方法。初始化 Promise 的状态为 pending。
2.实现一个Promise类
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)
}
现在已经实现了这个Promise类,还要实现Promise的then方法,
then 方法会传入两个函数作为参数,分别作为 promise 对象 resolve 和 reject 的处理函数。
then 方法有以下特点:
1.then 函数需要返回一个新的 promise 对象
2.执行 then 函数的时候,这个 promise 的状态可能还没有被扭转为 fulfilled 或 rejected
3.一个 promise 对象可以同时多次调用 then 函数
3.实现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 中的函数拿出来执行
})
}
}
this.</