const PENDING='pending'
const RESOLVED='resolve'
const REJECTED='rejected'
function myPromise(fn){
var that=this
this.value=''
this.resolveCallbacks=[]
this.rejectCallbacks=[]
this.state=PENDING
function resolve(value){
if(that.state==PENDING){
that.value=value
that.state=RESOLVED
that.resolveCallbacks.map(cb=>{cb(that.value)})
}
}
function reject(value){
if(that.state==PENDING){
that.value=value
that.state=REJECTED
that.rejectCallbacks.map(cb=>{cb(that.value)})
}
}
try{
fn(resolve,reject)
}catch(e){
reject(e)
}
}
myPromise.prototype.then=function(resolveFn,rejectFn){
var that=this
if(that.state==PENDING){
that.resolveCallbacks.push(resolveFn)
that.rejectCallbacks.push(rejectFn)
}else if(that.state==RESOLVED){
resolveFn(that.value)
console.log('resolved')
}else{
rejectFn(that.value)
}
}
var f=function(){
return new myPromise((resolve,reject)=>{
console.log("1")
setTimeout(function(){
console.log("2")
resolve(3)
},1000)
})
}
f().then((res)=>{
console.log(res)
})
实现 es6 Promise 原理
猜你喜欢
转载自blog.csdn.net/weixin_41531446/article/details/88665740
今日推荐
周排行