30行代码只能写个demo,但主要还是学习实现思路吧,先来了解一下Promise相关规范:
状态
1、Promise
只有三种状态:Pending、Fulfilled、Rejected
。
2、Pending
可以转换为另外两种状态,Promise
一旦变为Fulfilled
、Rejected
状态后不允许再更改状态。
then
1、Promise
必须提供一个 then
方法用于传入 Promise
兑现和拒绝后的回调函数,所以then
接受两个参数分别是onFulFilled, onRejected
2、then
方法必须返回一个 promise
对象,从而实现链式调用
3、onFulFilled
的入参,是传入Promise.resolve
的值,或者是上一个then
里return
的值
4、onFulFilled
如果不是函数,则会被替换为(x) => x
,相当于把值往后传递
const PENDING = 'PENDING', RESOLVED = 'FULFILLED', REJECTED = 'REJECTED';
class _Promise {
constructor(executor) {
this.state = PENDING; // 默认状态为 PENDING
this.value = undefined; // 存放成功状态的值,默认为 undefined
this.onResolvedCallback = [] // 存放回调函数
this.resolve = this.resolve.bind(this);
executor(this.resolve) // 执行new Promise 时传入的函数
}
resolve(value) {
queueMicrotask(() => { //创建一个微任务
if (this.state !== PENDING) return // 状态不为PENDING时直接返回
this.state = RESOLVED; // 修改状态
this.value = value; // 存储成功的值
this.onResolvedCallback.forEach(fn => fn(this.value)) // 执行成功的回调函数
})
}
then(onFulFilled) {
return new _Promise((resolve) => { // 返回一个新的Promise
onFulFilled = typeof onFulFilled === 'function' ? onFulFilled : v => v // 如果不是函数就返回原值
if (this.state === RESOLVED) { // 如果状态为RESOLVED
resolve(onFulFilled(this.value)) // 执行成功的回调函数
}
if (this.state === PENDING) { // 如果状态为PENDING
this.onResolvedCallback.push((v) => resolve(onFulFilled(v))) // 将成功的回调函数存储起来
}
})
}
}
测试代码
new _Promise((resolve, rejected) => {
setTimeout(() => {
resolve(4)
}, 500)
})
.then(res => {
console.log(res) // 输出:4
}).then(res => {
console.log(res) // 输出:undefined
return 8
}).then(res => {
console.log(res) // 输出:8
})