手写Promise自行封装 简化版与完整版

Promise 简化版实现 resolve reject throw回调

// 原生promise
let p = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('OK')
    },1000)
})
// 自定义Promise  简化版实现 resolve reject throw回调
function Promise(executor){
    //添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    //保存实例对象的this值  避免指向window
    const self = this
    // 声明属性保持回调函数
    this.callbacks = []
    function resolve(data){
        // 修改promise状态(promiseState)
        self.PromiseState = 'fulfilled'// fulfilled
        //设置结果值(promiseResult)
        self.PromiseResult = data
    }
    function reject(data){
        self.PromiseState = 'rejected'
        //设置结果值(promiseResult)
        self.PromiseResult = data
    }
    try{
        //执行器函数内部同步调用
        executor(resolve,reject)
    }catch(e){
        //抛出异常时 修改promise对象状态
        reject(e)
    }
}
// 封装resolve方法
Promise.resolve = function(value){
    //返回Promise对象
    return new Promise((resolve,reject)=>{
        if(value instanceof Promise){
            value.then(v=>{
                resolve(v)
            },r=>{
                reject(r)
            })
        }else{
            // 状态设置为成功
            resolve(value)
        }
    })
}
//封装Reject方法
Promise.reject = function(reason){
    return new Promise((resolve,reject)=>{
        reject(reason)
    })
}

promise完整版实现

// 对promise重复代码的封装
// 原生promise
let p = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('OK')
    },1000)
})
p.then(value=>{
    console.log(value)
},reason=>{
    console.log(reason)
})

p.catch(reason=>{
    console.warn(reason)
})

// 自定义Promise
function Promise(executor){
    //添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    //保存实例对象的this值  避免指向window
    const self = this
    // 声明属性保持回调函数
    this.callbacks = []
    function resolve(data){
        // 判断状态
        if(self.PromiseState !== "pending"){
            return;
        }
        // 修改promise状态(promiseState)
        self.PromiseState = 'fulfilled'// fulfilled
        //设置结果值(promiseResult)
        self.PromiseResult = data
        //执行异步pending成功的回调
        //if(self.callback.onResolved){
        //   self.callback.onResolved(data)
        //}
        setTimeout(()=>{
       		 self.callbacks.forEach(item=>{
            	item.onResolved(data)
        	})     
        })
    }
    function reject(data){
        if(self.PromiseState !== "pending")return;
        // 修改promise状态(promiseState)
        self.PromiseState = 'rejected'
        //设置结果值(promiseResult)
        self.PromiseResult = data
        //执行异步pending成功的回调
        //if(self.callback.onRejected){
        //self.callback.onRejected(data)
        //}
        setTimeout(()=>{
            self.callbacks.forEach(item=>{
                item.onRejected(data)
            })
        })
    }
    try{
        //执行器函数内部同步调用
        executor(resolve,reject)
    }catch(e){
        //抛出异常时 修改promise对象状态
        reject(e)
    }
}
//添加then方法
Promise.prototype.then= function(onResolve,onRejected){
    const self = this
    if(typeof onRejected !== 'function'){
        onRejected = reason=>{
            throw reason
        }
    }
    
    if(typeof onResolved !== 'function'){
        onResolved = value=>{
            return value
        } //  也可以简写为 onResolved = value => value
    }
    return new Promise((resolve,reject)=>{
        // 封装函数
        function callback(type){
            try{
                let result = type(self.PromiseResult)
                if(result instanceof Promise){
                    result.then(v=>{
                        resolve(v)
                    },r=>{
                        reject(r)
                    })
                }else{
                    resolve(result)
                }}catch(e){
                    reject(e)
                }
        }
        
        //调用回调函数
        if(this.PromiseState == 'fulfilled'){
            //获取回调函数的执行结果
            setTimeout(()=>{
                callback(onResolved)
            })
        }
        if(this.PromiseState == 'rejected'){
            setTimeout(()=>{
                onRejected(this.PromiseResult)
            })
        }
        //判断异步pending状态
        if(this.PromiseState == 'pending'){
            //保存回调函数
            this.callbacks.push({
                onResolved:function(){
                   callback(onResolved)
                },
                onRejected:function(){
                    callbacck(onRejected)
                }
            })
        }
    })
}
// 添加catch方法 catch方法的封装与异常穿透
Promise.prototype.catch = function(onRejected){
    return this.then(undefined,onRejected)
}
// 封装resolve方法
Promise.resolve = function(value){
    //返回Promise对象
    return new Promise((resolve,reject)=>{
        if(value instanceof Promise){
            value.then(v=>{
                resolve(v)
            },r=>{
                reject(r)
            })
        }else{
            // 状态设置为成功
            resolve(value)
        }
    })
}
//封装Reject方法
Promise.reject = function(reason){
    return new Promise((resolve,reject)=>{
        reject(reason)
    })
}
// promise的all方法
Promise.all = function(promises){
    //返回结果为promise对象
    return new Promise((resolve,reject)=>{
        //遍历
        //声明变量 
        let count = 0;
        //存放所有promise对象结果的数组
        let arr = [];
        for(let i = 0;i<= promises.length;i++){
            promises[i].then(v=>{
                //得知对象状态是成功
                //每个promise对象都成功才能调用resolve方法
                // 将当前promise对象结果存入数组中
                // arr.push(v)  异步请求 顺序可能不匹配
                arr[i] = v;
                count++;
                if(count == promises.length){
                 	resolve(arr)
                }
            },r=>{
                reject(r)
            })
        }
    })
}
// Promise的race方法
Promise.race = function(promises){
    return new Promise((resolve,reject)=>{
        for(let i = 0;i<promises.length;i++){
            promises[i].then(v=>{
                //修改返回对象状态为成功
            	resolve(v)   
            },r=>{
                reject(r)
            })
        }
    })
}

将Promise 封装成类

//  将构造函数封装成类 
class Promise{
    //构造方法
    constructor(executor){
        //添加属性
        this.PromiseState = 'pending'
        this.PromiseResult = null
        //保存实例对象的this值  避免指向window
        const self = this
        // 声明属性保持回调函数
        this.callbacks = []
        function resolve(data){
            // 判断状态
            if(self.PromiseState !== "pending"){
                return;
            }
            // 修改promise状态(promiseState)
            self.PromiseState = 'fulfilled'// fulfilled
            //设置结果值(promiseResult)
            self.PromiseResult = data
            //执行异步pending成功的回调
            //if(self.callback.onResolved){
            //   self.callback.onResolved(data)
            //}
            setTimeout(()=>{
                self.callbacks.forEach(item=>{
                    item.onResolved(data)
                })     
            })
        }
        function reject(data){
            if(self.PromiseState !== "pending")return;
            // 修改promise状态(promiseState)
            self.PromiseState = 'rejected'
            //设置结果值(promiseResult)
            self.PromiseResult = data
            //执行异步pending成功的回调
            //if(self.callback.onRejected){
            //self.callback.onRejected(data)
            //}
            setTimeout(()=>{
                self.callbacks.forEach(item=>{
                    item.onRejected(data)
                })
            })
        }
        try{
            //执行器函数内部同步调用
            executor(resolve,reject)
        }catch(e){
            //抛出异常时 修改promise对象状态
            reject(e)
        }
    }

    //then方法封装
    then(onResolved,onRejected){
        const self = this
        if(typeof onRejected !== 'function'){
            onRejected = reason=>{
                throw reason
            }
        }
        
        if(typeof onResolved !== 'function'){
            onResolved = value=>{
                return value
            } //  也可以简写为 onResolved = value => value
        }
        return new Promise((resolve,reject)=>{
            // 封装函数
            function callback(type){
                try{
                    let result = type(self.PromiseResult)
                    if(result instanceof Promise){
                        result.then(v=>{
                            resolve(v)
                        },r=>{
                            reject(r)
                        })
                    }else{
                        resolve(result)
                    }}catch(e){
                        reject(e)
                    }
            }
            
            //调用回调函数
            if(this.PromiseState == 'fulfilled'){
                //获取回调函数的执行结果
                setTimeout(()=>{
                    callback(onResolved)
                })
            }
            if(this.PromiseState == 'rejected'){
                setTimeout(()=>{
                    onRejected(this.PromiseResult)
                })
            }
            //判断异步pending状态
            if(this.PromiseState == 'pending'){
                //保存回调函数
                this.callbacks.push({
                    onResolved:function(){
                       callback(onResolved)
                    },
                    onRejected:function(){
                        callbacck(onRejected)
                    }
                })
            }
        })
    }
    //catch方法封装
    catch(onRejected){
        return this.then(undefined,onRejected)
    }
    // 封装resolve方法  rsolve属于类 而不是实例对象
    static resolve(value){
        //返回Promise对象
        return new Promise((resolve,reject)=>{
            if(value instanceof Promise){
                value.then(v=>{
                    resolve(v)
                },r=>{
                    reject(r)
                })
            }else{
                // 状态设置为成功
                resolve(value)
            }
        })
    }
    // 封装reject方法
    reject(reason){
        return new Promise((resolve,reject)=>{
            reject(reason)
        })
    }
    // promise的all方法
    static all(promises){
        //返回结果为promise对象
        return new Promise((resolve,reject)=>{
            //遍历
            //声明变量 
            let count = 0;
            //存放所有promise对象结果的数组
            let arr = [];
            for(let i = 0;i<= promises.length;i++){
                promises[i].then(v=>{
                    //得知对象状态是成功
                    //每个promise对象都成功才能调用resolve方法
                    // 将当前promise对象结果存入数组中
                    // arr.push(v)  异步请求 顺序可能不匹配
                    arr[i] = v;
                    count++;
                    if(count == promises.length){
                        resolve(arr)
                    }
                },r=>{
                    reject(r)
                })
            }
        })
    }
    // Promise的race方法
    static race(promises){
        return new Promise((resolve,reject)=>{
            for(let i = 0;i<promises.length;i++){
                promises[i].then(v=>{
                    //修改返回对象状态为成功
                    resolve(v)   
                },r=>{
                    reject(r)
                })
            }
        })
    }

}

你可能感兴趣的:(前端,ecmascript)