class PromiseNew{
constructor(fn){
this.satate="PENDING"
this.doneList = []
this.failList = []
fn(this.resolve.bind(this) ,this.reject.bind(this)) //fn是外部函數,裏面this已經改變,所以要綁定bind
}
done(handle){
if(typeof handle ==="function"){
this.doneList.push(handle)
}else{
throw new Error("缺少回調函數")
}
return this
}
fail(handle){
if(typeof handle ==="function"){
this.failList.push(handle)
}else{
throw new Error("缺少回調函數")
}
return this
}
then(success,fail){
this.done(success || function(){}).fail(fail || function(){})
return this
}
resolve () {
this.satate="RESOLVED"
let args =Array.prototype.slice.call(arguments)
setTimeout(function(){
this.doneList.forEach((item, key) => {
let arg = item.apply(null,args) //實際上doneList中第一個函數的返回值是第二個函數的參數
args = [] //清空參數
args.push(arg)
});
this.doneList =[] //清空數據
}.bind(this), 200)
return this
}
reject(){
this.satate="REJECTED"
let args =Array.prototype.slice.call(arguments)
setTimeout(function(){
this.failList.forEach((item, key) => {
let arg = item.apply(null,args)
args = []
args.push(arg)
});
this.failList =[] //清空數據
}.bind(this), 200)
console.log("reject 執行")
}
}
new PromiseNew((resolve,reject)=>{
resolve("啪啪啪")
reject()
console.log("ben")
}).then((value)=>{
console.log("success",value)
return 9999
},()=>{
console.log("fail")
})