美文网首页
promise的简单实现

promise的简单实现

作者: DCbryant | 来源:发表于2017-11-14 17:13 被阅读13次
class MyPromise{
    constructor(fn){
        this.queue = []
        this.succ_res = null
        this.fail_res = null
        this.status = 'pending'

        fn((...args) => {//resolve
            this.succ_res = args
            this.status = 'fulfilled'
            this.queue.forEach((json) => {
                json.fn1(...args)
            })
        },(...args) => {//reject
            this.fail_res = args
            this.status = 'rejected'
            this.queue.forEach((json) => {
                json.fn2(...args)
            })
        })
    }

    then(fn1,fn2){
        if(this.status === 'fulfilled'){
            fn1(...this.succ_res)
        }else if(this.status === 'rejected'){
            fn2(...this.fail_res)
        }else{
            this.queue.push({fn1,fn2})
        }
    }
}

MyPromise.all = function(arr){
    let result = []
    return new MyPromise(function(resolve,reject){
        let i = 0

        next()

        function next(){
            arr[i].then(function(res){
                result.push(res)
                i++
                if(i == arr.length){
                    resolve(result)
                }else{
                    next()
                }
            },reject)
        }
    })
}

let mp = new MyPromise(function(resolve,reject){
    setTimeout(function(){
        resolve(12)
    },500)
})
mp.then(function (num){
    console.log(num);
}, function (){
    alert('错误')
})

let mp1 = new MyPromise(function(resolve,reject){
    setTimeout(function(){
        resolve(233)
    },800)
})

MyPromise.all([mp,mp1]).then(function(arr){
    let [res1,res2] = arr
    console.log(res1)
    console.log(res2)
},function(error){
    console.log(error)
})

相关文章

网友评论

      本文标题:promise的简单实现

      本文链接:https://www.haomeiwen.com/subject/piufvxtx.html