简单promise的实现

 		const PENDING = 'pending'
        const RESOLVED = 'resolved'
        const REJECTED = 'rejected'
        function MyPromise(fn) {
        const that = this
        that.state = PENDING
        that.value = null
        that.resolvedCallbacks = []
        that.rejectedCallbacks = []
        //resolve 依赖派发
        function resolve (value){
          setTimeout(function(){//模拟异步操作
            if (that.state === PENDING){
                that.state=RESOLVED
                that.value=value
                that.resolvedCallbacks.map(item => item(that.value))
            }
          })
        }
        reject 依赖派发
        function reject (value) {
            if(that.state === PENDING) {
                that.state = REJECTED
                that.value = value
                that.rejectedCallbacks.map(item => item(that.value))
            }
        }
        try{
          //调用用户传入的回调函数fn
            fn(resolve,reject)
        }catch(e){
          //如果报错就执行reject
            reject(e)
        }
        }

        //在这个构造函数的原型上添加then方法
        MyPromise.prototype.then = function (onFulfilled,onRejected) {
            const that = this
            onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v  //不是函数就包装成一个函数以便于后面的执行
            onRejected = typeof onRejected === 'function' ? onRejected : r => {throw r}
            if (that.state === PENDING){
                that.resolvedCallbacks.push(onFulfilled)
                that.rejectedCallbacks.push(onRejected)
            }
            if(that.state === RESOLVED){
                onFulfilled(that.value)
            }
            if(that.state === REJECTED){
                onRejected(that.value)
            }
        }
        console.log('a')
        //实现非等待状态, 加个setTimeout就是等待状态
        new MyPromise((resolve, reject) => {
            resolve(1)
        }).then(value => {
        console.log(value)
        })
        console.log('b')

你可能感兴趣的:(简单promise的实现)