const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromise(fn) {
let that = this
that.state = PENDING
that.value = undefined
//存储成功状态的回调函数
that.resolvedList = []
//存储失败状态的回调函数
that.rejectedList = []
//立即执行Promise中的函数fn,fn接受resolve和reject函数作为参数
fn(resolve,reject)
function resolve(x) {
that.state = RESOLVED
that.value = x
//new Promise实例化后去调用then()方法,如果promise对象的状态还是pending,
// 会先把对应的回调函数存储到resolvedList、rejectedList数组中,
//等到执行resolve的时候,去对应的数组中找到要执行的回调函数,把resolve传的值传递给回调函数
if (that.resolvedList.length != 0){
that.resolvedList.forEach(function (fn,index) {
fn(that.value)
})
}
}
function reject(x) {
that.state = REJECTED
that.value = x
if (that.rejectedList.length != 0){
that.rejectedList.forEach(function (fn,index) {
fn(that.value)
})
}
}
}
MyPromise.prototype.then = function (fn1,fn2) {
let that = this
//判断fn1/2是否是函数类型
fn1 = typeof fn1 == 'function'? fn1:(msg)=>console.log(msg)
fn2 = typeof fn2 == 'function'? fn2:(err)=>console.log(err)
//new Promise实例化后,状态没有改变,就预先把回调函数存到对应的数组中,
// 待到执行resolve或者reject函数的时候,去对应数组中找回调函数
if (that.state == PENDING){
that.resolvedList.push(fn1)
that.rejectedList.push(fn2)
}
//new Promise实例化后,状态为成功状态,调用then()方法就直接执行回调函数,并返回新的promise对象
if (that.state == RESOLVED){
let res = fn1(that.value)
if(res instanceof MyPromise){
return res
}else {
return new MyPromise(function (resolve,reject) {
resolve()
})
}
}
if (that.state == REJECTED){
let res = fn2(that.value)
if(res instanceof MyPromise){
return res
}else {
return new MyPromise(function (resolve,reject) {
resolve()
})
}
}
}
let promise = new MyPromise(function (res,rej) {
setTimeout(res,3000,789)
console.log(123)
})
promise.then(msg=>console.log(msg))
console.log(promise)
自己实现一个简易的promise
最新推荐文章于 2024-02-25 15:34:42 发布