本文记录一下Promise最简单的实现,以巩固基础
Promise是十分重要的,解决了很多问题,如回调地狱;想更加深入的了解Promise的同学可以参照Promises A+规范
第一版(最基础版本)
//main.js
//定义三种状态
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class MyPromise {
//创建实例的时候需要传入回调函数
constructor(callback) {
//初始化自身状态
this.state = PENDING
this.value = undefined
this.reason = undefined
//resolve执行的逻辑
const resolve = (value) => {
//先判断是否为pending状态
//因为Promise的状态已经改变就不不能再变了
if (this.state === PENDING) {
//将状态进行修改
this.state = FULFILLED
//修改value
this.value = value
}
}
//reject执行逻辑,与resolve差不多
const reject = (reason) => {
if (this.state === PENDING) {
this.state = REJECTED
this.reason = reason
}
}
//执行callback
//callback中可能抛出异常
try{
callback(resolve, reject)
} catch(e) {
reject(e)
}
}
//then函数逻辑
then(onResolve, onRejected) {
//判断状态,执行对应回调函数
if (this.state === FULFILLED) {
onResolve(this.value)
}
if (this.state === REJECTED) {
onRejected(this.reason)
}
}
}
//简单测试一下
const p = new MyPromise((resolve, reject) => {
console.log('promise')
resolve('fulfilled')
})
p.then((res) => {
console.log(res)
},
(reason) => {
console.log(reason)
})
不出所料 ,结果为:
promise
fulfilled
所以这里实现的最简易版本的Promise是没问题的
第二版(异步修改状态)
先做个测试:
如果你执行如下测试,你会发现情况不对
const p = new MyPromise((resolve, reject) => {
console.log('promise')
setTimeout(() => {
resolve('fulfilled')
}, 1000)
})
p.then((res) => {
console.log(1, res)
},
(reason) => {
console.log(reason)
})
p.then((res) => {
console.log(2, res)
},
(reason) => {
console.log(reason)
})
打印结果只有promise
上一个最简易版的then是同步执行的,当state没有改变时,不会执行任何一个回调
代码实现
//main.js
//与第一版相同的地方就不做解释了
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class MyPromise {
constructor(callback) {
this.state = PENDING
this.value = undefined
this.reason = undefined
//增加两个回调函数的数组,将then中的回调函数存在里面
this.resolveCallback = []
this.rejectedCallback = []
//这里就先去看一下then函数的处理
const resolve = (value) => {
if (this.state === PENDING) {
this.state = FULFILLED
this.value = value
//执行resolve的同时,将resolveCallback中的所有回调函数执行
this.resolveCallback.forEach(fn => fn())
}
}
const reject = (reason) => {
if (this.state === PENDING) {
this.state = REJECTED
this.reason = reason
//执行reject的同时,将rejectedCallback中的所有回调函数执行
this.rejectedCallback.forEach(fn => fn())
}
}
try{
callback(resolve, reject)
} catch(e) {
reject(e)
}
}
then(onResolve, onRejected) {
//当调用then的时候,状态还未发生改变,那么我们就先将回调函数存起来
if (this.state === PENDING) {
this.resolveCallback.push(() => onResolve(this.value))
this.rejectedCallback.push(() => onRejected(this.reason))
}
if (this.state === FULFILLED) {
onResolve(this.value)
}
if (this.state === REJECTED) {
onRejected(this.reason)
}
}
}
//小测试一波
const p = new MyPromise((resolve, reject) => {
console.log('promise')
setTimeout(() => {
resolve('fulfilled')
}, 1000)
})
p.then((res) => {
console.log(1, res)
},
(reason) => {
console.log(reason)
})
p.then((res) => {
console.log(2, res)
},
(reason) => {
console.log(reason)
})
测试结果为:
promise
1 fulfilled
2 fulfilled
OK,那么就可以了