美文网首页
实现一个简单的Promise

实现一个简单的Promise

作者: 葶寳寳 | 来源:发表于2019-08-22 14:40 被阅读0次

    先从一个简单的应用倒推出简单的Promise实现过程。

    🌰

    let p = new Promise((resolve, reject) => {
        console.log('我被执行了~');
        resolve('success');
    });
     
    // 我被执行了~
     
    p.then(res => {
        console.log(res);
    }, err => {
        console.log(err);
    });
    // success
    

    Promise的参数是一个带有两个参数的函数executor。由上边的执行结果可知,当我们new一个Promise对象时,executor这个函数会被执行;当我们在该函数里调用reslove/reject时,该Promise实例的状态就会发生改变,所以需要一个变量来记录状态,且状态变换是不可逆的,只能从 pending => rejectedpending => fulfilled

    1.首先,我们要实现的Promise对象要满足上边提到的两点:

    let PENDING = 'PENDING'
    let FULFILLED = 'FULFILLED'
    let REJECTED = 'REJECTED'
     
    class Promise{
        constructor(executor){
            this.status = PENDING
            this.value = undefined
            this.reason = undefined
     
            let resolve = value => {
                if(this.status === PENDING) {
                    this.status = FULFILLED
                    this.value = value
                }
            }
            let reject = reason => {
                if(this.status === PENDING) {
                    this.status = REJECTED
                    this.reason = reason   
                }
            }
            try{
                executor(resolve, reject) 
            } catch(e) {  // 对执行executor时产生的错误进行处理
                reject(e);
            }
        }
    }
    

    这部分内容是比较好理解的.
    2.然后接下来就是对then方法的实现:then方法主要提供了状态从 PENDING => FULFILLEDPENDING => REJECTED 的要执行的回调,所以then方法同样需要两个参数。

    class Promise{
        constructor(executor){
            this.status = PENDING
            this.value = value
            this.reason = reason
     
            let resolve = value => {
                if(this.status === PENDING) {
                    this.status = FULFILLED
                    this.value = value
                }
            }
            let reject = reason => {
                if(this.status === PENDING) {
                    this.status = REJECTED
                    this.reason = reason   
                }
            }
     
            try{
                executor(resolve, reject) 
            } catch(e) {  // 对执行executor时产生的错误进行处理
                reject(e);
            }
        }
     
        then(onFulfilled, onRejected) {
            if(this.status === FULFILLED) {
                onFulfilled(this.value)
            }
             
            if(this.status === RESOLVED) {
                onRejected(this.reason)
            }
        }
    }
    

    以上实现的Promise中只支持同步代码。若执行器中有异步任务(比如:setTimeout)存在时,将不会有输出:

    let p = new Promise((resolve, reject) => {
        setTimeOut(() => {resolve('success')}, 0)
    });
     
    p.then(res => {
        console.log(res);
    }, err => {
        console.log(err);
    });
    //
    

    3.接下来,我们需要做进一步的优化,支持异步任务:

    let PENDING = 'PENDING'
    let FULFILLED = 'FULFILLED'
    let REJECTED = 'REJECTED'
    
    class Promise {
       constructor(executor) {
           this.status = PENDING
           this.value = undefined
           this.reason = undefined
           this.onFulfilledCallbacks = []
           this.onRejectedCallbacks = []
    
           let resolve = value => {
               if(this.status === PENDING) {
                   this.status = FULFILLED
                   this.value = value
                   this.onFulfilledCallbacks.forEach(onFulfilled => onFulfilled()) // 对异步任务的处理
               }
           }
    
           let reject = reason => {
               if(this.status === PENDING) {
                   this.status = REJECTED
                   this.reason = reason
                   this.onRejectedCallbacks.forEach(onRejected => onRejected()) // 对异步任务的处理
               }
           }
    
           try {
               executor(resolve, reject)
           } catch(e) {
               reject(e)
           }
       }
    
       then(onFulfilled, onRejected) {
           if(this.status === FULFILLED) {
               onFulfilled(this.value)
           }
           if(this.status === REJECTED) {
               onRejected(this.reason)
           }
           if(this.status === PENDING) {
               this.onFulfilledCallbacks.push(() => { onFulfilled(this.value) })
               this.onRejectedCallbacks.push(() => { onRejected(this.reason) })
           }
       }
    }
    

    当状态为PENDING时,将对应的onFulfilledonRejected方法存起来,直到状态改变时再去执行。

    至此,已经实现了一个简单的Promise,上边实现的Promise只支持 P.then( res=> {}, (err) => {})这样形式的调用,不支持链式调用,因为上边实现的then方法并没有返回Promise对象。所以还需要对then方法做进一步的改造,让其返回一个Promise

    4.改造then方法,让其返回Promise,支持链式调用

    let PENDING = 'PENDING'
    let FULFILLED = 'FULFILLED'
    let REJECTED = 'REJECTED'
     
    class Promise {
        constructor(executor) {
            this.status = PENDING
            this.value = undefined
            this.reason = undefined
            this.onFulfilledCallbacks = []
            this.onRejectedCallbacks = []
     
            let resolve = value => {
                if(this.status === PENDING) {
                    this.status = FULFILLED
                    this.value = value
                    this.onFulfilledCallbacks.forEach(onFulfilled => onFulfilled()) // 对异步任务的处理
                }
            }
     
            let reject = reason => {
                if(this.status === PENDING) {
                    this.status = REJECTED
                    this.reason = reason
                    this.onRejectedCallbacks.forEach(onRejected => onRejected()) // 对异步任务的处理
                }
            }
     
            try {
                executor(resolve, reject)
            } catch(e) {
                reject(e)
            }
        }
     
        then(onFulfilled, onRejected) {
            onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : r => { return r }
            onRejected = typeof onRejected === 'function' ? onRejected : j => { return j }
     
            return new Promise((resolve, reject) => {
                if(this.status === FULFILLED) {
                    try {
                        let ret = onFulfilled(this.value)
                        if(ret instanceof Promise) {
                            ret.then(resolve, reject)
                        } else {
                            resolve(ret)
                        }
                    } catch(e) {
                        reject(e)
                    }
                }
     
                if(this.status === REJECTED) {
                    try {
                        let ret = onRejected(this.reason)
                        if(ret instanceof Promise) {
                            ret.then(resolve, reject)
                        } else {
                            reject(ret)
                        }
                    } catch(e) {
                        reject(ret)
                    }
                }
     
                if(this.status === PENDING) {
                    this.onFulfilledCallbacks.push(() => {
                        try {
                            let ret = onFulfilled(this.value)
                            if(ret instanceof Promise) {
                                ret.then(resolve, reject)
                            } else {
                                resolve(ret)
                            }
                        } catch(e) {
                            reject(e)
                        }
                    })
     
                    this.onRejectedCallbacks.push(() => {
                        try {
                            let ret = onRejected(this.reason)
                            if(ret instanceof Promise) {
                                ret.then(resolve, reject)
                            } else {
                                reject(ret)
                            }
                        } catch(e) {
                            reject(ret)
                        }
                    })
                }
            })
        }
     
        catch(onRejected) {  // catch方法其实就是对then方法的调用
            return this.then(null, onRejected)
        }
    }
    

    至此,我们已经实现了一个可支持链式调用的Promise方法~

    误区
    1.在执行器中调用的resolve方法,并不是在then方法中添加的方法。resolve / reject 是在 Promise 对象中定义好的,是用来改变状态的(PENDING =>FULFILLED / PENDING => REJECTED),而then方法只是指定的变为FULFILLED / REJECTED执行的方法。

    let p = new Promise((resolve, reject) => {
       resolve('success')
    }) 
    p.then( res => console.log(res), err => console.log(err) )
    

    实现promise.all就相对简单了:

    Promise.prototype.all = function(promises) {
        return new Promise((resolve, reject) => {
            if(!isArrary(promises)) {
                reject(new Error('arguments must be array'))
            }
            let res = [];
            for(let i = 0; i < promises.length; i++) {
                Promise.resolve(promises[i]).then(r => {
                    res.push(r);
                    if(res.length === promises.length) {
                        return resolve(res);
                    }
                })
                .catch(j => {
                    return reject(j);
                })
            }
        })
    }
    

    相关文章

      网友评论

          本文标题:实现一个简单的Promise

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