简单的 Promies 封装
function Promiss(fn) {
this.state = 'pending' //当前状态
this.value = null // 成功执行时得到的数据
this.reason = null // 执行失败时的返回值
this.resolveCallbacks = [] // 存储回调函数的数组
this.rejectCallbacks = []
resolve = value => {
this.state = 'resolver'
this.value = value
this.resolveCallbacks.map(cb => cb(this.value))
}
reject = reason => {
this.state = 'rejected'
this.value = value
this.resolveCallbacks.map(cb => cb(this.reason))
}
try {
fn(resolve, reject)
} catch (error) {
reject(error)
}
}
Promiss.prototype.then = function (onFulfilled, onRejected) {
if (this.state === 'pending') {
this.resolveCallbacks.push(onFulfilled)
this.rejectCallbacks.push(onRejected)
}
}
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ok')
}, 2000)
})
.then(res => {
console.log(res);
})
Promise 原理
- promise 的出现是为了解决回调地狱的问题,关键在于利用了 js 异步操作最后执行的特性,将回调方法的传递单独操作,不必担心异步代码执行过早
- promise 的时间线如下
- 执行构造参数里的同步代码,将异步操作暂时挂起
- 将 then 方法传入的回调函数放入到相应的回调队列里
- 开始执行异步操作,执行至 resolve / reject 方法
- 在 resolve / reject 方法中改变 promise 的状态,执行 then 方法在步骤2里传入的回调函数
![](https://img2020.cnblogs.com/blog/1948214/202007/1948214-20200702214211120-272128172.png)