- promise 有三种状态:等待态,成功态,失败态。状态改变后不可逆。
- promise.then 有两个参数 第一个参数是成功的回调,第二个参数是失败的回调
const RESOLVE = "reslove"
const REJECT = "reject"
const PENDING = "pending"
class Promise{
constructor(executor){
this.status = PENDING
this.value = undefined
this.reason = undefined
this.onResolvedCallbacks = []
this.onRejectedCallbacks = []
let reslove = (value)=>{
this.status = RESOLVE
this.value = value
this.onResolvedCallbacks.forEach(item=>item())
}
let reject = (reason)=>{
this.status = REJECT
this.reason = reason
this.onRejectedCallbacks.forEach(item=>item())
}
try{
executor(reslove,reject)
}catch(e){
reject(e)
}
}
then(onFulfilled, onRejected){
if(this.status === RESOLVE){
onFulfilled(this.value)
}
if(this.status === REJECT){
onRejected(this.reason)
}
if(this.status === PENDING){
this.onResolvedCallbacks.push(()=>{
onFulfilled(this.value)
})
this.onRejectedCallbacks.push(()=>{
onRejected(this.reason)
})
}
}
}
let promiseA = new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve("aaa")
},2000)
})
promiseA.then((res)=>{
console.log("success1",res)
})
promiseA.then((res)=>{
console.log("success2",res)
})
let promiseB = new Promise((resolve, reject)=>{
console.log("1")
reject("aaa")
})
console.log(2)
promiseB.then((res)=>{
console.log("success",res)
},(err)=>{
console.log("err",err)
})