实现简单的promise

实现promise必须符合promise A plus的规范 官方网址 https://promisesaplus.com/

  • 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)
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。