Promise的调用流程:
- Promise的构造方法接收一个回调函数executor(),在new Promise()时就立刻执行这个回调函数executor()。
- 回调函数内部的异步任务被放入宏/微任务队列,等待执行
- then()被执行,收集成功/失败回调,放入成功/失败队列
- 回调函数executor()的异步任务被执行,触发resolve/rejuce,从成功/失败队列中取出回调依次执行
Promise规范
- Promise本质是一个状态机,且状态只能为以下三种:Pending(等待态)、Fulfilled(执行态)、Rejected(拒绝态),状态的变更是单向的,只能从Pending -> Fulfilled 或 Pending -> Rejected,状态变更不可逆。
- then方法接收两个可选参数,分别对应状态改变时触发的回调。then方法返回一个promise。then 方法可以被同一个 promise 调用多次。
const PENDING = 'pending'
cosnt FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
constructor(executor) {
this._status = PENDING
this._resolveQueue = []
this._rejectQueue = []
let _resolve = (val) => {
if (this._status !== PENDING) return
this._status = FULFILLED
while(this._resolveQueue.length) {
const callback = this._resolveQueue.shift()
callback(val)
}
}
let _reject = (val) => {
if (this._status !== PENDING) return
this._status = REJECTED
while(this._rejectQueue.length) {
const callback = this._rejectQueue.shift()
callback(val)
}
}
executor(_resolve, _reject)
}
then(resolveFn, rejectFn) {
this._resolveQueue.push(resolveFn)
this._rejectQueue.push(rejectFn)
}
}