手写promise
class SxPromise{
static PENDING = 'pending'
static FULFLED = "success"
static REJECT = 'failed'
constructor(fun){
this.status = SxPromise.PENDING
this.res = null
this.fulLIst = []
this.failLIst = []
try{
fun(this.resolve.bind(this),this.reject.bind(this))
}catch(err){
this.reject(err)
}
}
resolve(res){
setTimeout(()=>{
if(this.status === SxPromise.PENDING){
this.status = SxPromise.FULFLED
this.res = res
this.fulLIst.map(item=>{
item(res)
})
}
})
}
reject(err){
setTimeout(()=>{
if(this.status === SxPromise.PENDING){
this.status = SxPromise.REJECT
this.res = err
this.fulLIst.map(item=>{
item(err)
})
}
})
}
then(success,fail){
return new SxPromise((resolve,reject)=>{
success = typeof success === 'function' ? success : ()=>{}
fail = typeof fail === 'function' ? fail : ()=>{}
if(this.status === SxPromise.PENDING){
this.fulLIst.push(success)
this.failLIst.push(fail)
}
if(this.status === SxPromise.FULFLED){
success(this.res)
}
if(this.status === SxPromise.REJECT){
fail(this.res)
}
})
}
}
console.log('第一次');
let res = new SxPromise((resolve,reject)=>{
setTimeout(()=>{
console.log('第二次');
resolve('resolve。。。。')
console.log('第三次');
})
})
res.then((res)=>{
console.log(res);
}).then((res)=>{
console.log(11);
})
console.log('第四次');
版权声明:本文为qq_44929535原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。