简单手写一个promise

96 阅读1分钟

Promise 的出现解决了处理异步编程使用回调函数,层层嵌套的地狱回调问题,地狱回调易读性差逻辑不清晰,相信谁接手了一个这样的代码都要骂一句上写得什么玩意儿。当然了处理异步编程还有 async 和 await等方式,async 和 await 相比于promise又有一些优点。

这里简略写一个promise:

class Promise2 {
    status = 'pedding'
    succeed = function(){}
    fail = null
    
    constructor(fn) {
        fn(this.resolve.bind(this), this.rejected.bind(this))
    }
    
    resolve(value) {
        this.status = 'resolve'
        this.succeed(value)
        
    }
        
    rejected(value) {
        this.status = 'rejected'
        this.fail = value
    }
    
    then(succeed) {
       this.succeed = succeed
    }
}

let F = new Promise2((resolve, rejected)=>{
    setTimeout(()=>{
        resolve(123)
    },3000)
})
F.then(res => {
    console.log(res) // 3S后打印 123
})