手写简化版 Promise
思路:
- 声明状态#status = 'padding'
- 声明异步数组q
- 声明resolve
- 声明reject
- 声明this
class Promise2 {
#status = 'pending' // ES6:局部变量,且不能改变
/**
* 接受一个参数fn,返回的结果可能成功,也可能失败,但是仅返回一种情况
*/
constructor(fn){
/**
* this.q
* 两个参数:[0]resolve函数 和 [1]reject函数
*/
this.q = []
const resolve = (data) => {
// 1.等待状态 => 变为成功状态
this.#status = 'fulfilled'
// 2.获取执行函数数组
const f1f2 = this.q.shift()
// 3.防御性:防止不调用then和函数集合无数据
if(!f1f2 || !f1f2[0])return
// 4.执行成功函数
const x = f1f2[0].call(undefined,data)
/**
* 5.链式调用
* 异步:继续调用then
* 同步:不会出错,直接return
*/
if(x instanceof Promise2){
x.then(
data => {
resolve(data)
},
reason => {
reject(reason)
}
)
}else{
resolve(x)
}
}
const reject = (reason) => {
// 1。等待状态 => 变为失败状态
this.#status = 'rejected'
// 2.获取执行函数数组
const f1f2 = this.q.shift()
// 3.防御性:防止不调用then和函数集合无数据
if(!f1f2 || !f1f2[1])return
// 4.执行失败函数
const x = f1f2[1].call(undefined,reason)
/**
* 5.链式调用
* 异步:继续调用then
* 同步:不会出错,直接return
*/
if(x instanceof Promise2){
x.then(
data => {
resolve(data)
},
reason => {
reject(reason)
}
)
}else{
resolve(x)
}
}
// 6.返回值:最终执行
fn(resolve,reject) // fn.call(undefined,resolve,reject)
}
then(req,res){
// 7.把参数函数push执行数组中,等待执行即可
this.q.push([req,res])
//为了链式调用,继续.then
return this
}
}
使用方法:
const p = new Promise2(function (resolve, reject) {
setTimeout(() => {
// resolve('success')
reject('fail')
}, 3000)
})
p.then(
data => {
console.log(data)
},
error => {
console.error(error)
}
)