zoukankan      html  css  js  c++  java
  • promise 实现

    1实现异步调用
    const PENDDING = 'pendding',
        RESOLVED = 'resolved',
        REJECTED = 'rejected'
    	
        class myPromise {
            constructor(handler){
                this.status = PENDDING
                this.value = undefined
                this.resolveCallback = []
                this.rejectCallback = []
                let resolve = (value)=>{
                    if(this.status === PENDDING){
                        this.status = RESOLVED
                        this.value = value
                        this.resolveCallback.forEach((cb)=>{
                            cb()
                        })
                    }
                }
                let reject = (error)=>{
                    if(this.status === PENDDING){
                        this.status = REJECTED
                        this.reason = error
                        this.rejectCallback.forEach((cb)=>{
                            cb()
                        })
                    }
                }
                try{
                    handler(resolve,reject)
                }catch{
                    reject(error)
                }
            }
            then(onResolve=val=>val,onReject){
                if(this.status === PENDDING){
                    this.resolveCallback.push(()=>onResolve(this.value))
                }
                if(this.status === RESOLVED){
                    onResolve(this.value)
                }
                if(this.status === REJECTED){
                    onReject(this.reason)
                }
            }
        }
    
        new myPromise((resolve)=>{
            setTimeout(()=>{
                resolve(123)
            },2000)
        }).then((res)=>{
            console.log(res)
        })
    

    2.实现 链式调用并返回普通值 主要是promiseResultProduce这个函数

     const PENDDING = 'pendding',
        RESOLVED = 'resolved',
        REJECTED = 'rejected'
        class myPromise {
            constructor(handler){
                this.status = PENDDING
                this.value = undefined
                this.resolveCallback = []
                this.rejectCallback = []
                let resolve = (value)=>{
                    if(this.status === PENDDING){
                        this.status = RESOLVED
                        this.value = value
                        this.resolveCallback.forEach((cb)=>{
                            cb()
                        })
                    }
                }
                let reject = (error)=>{
                    if(this.status === PENDDING){
                        this.status = REJECTED
                        this.reason = error
                        this.rejectCallback.forEach((cb)=>{
                            cb()
                        })
                    }
                }
                try{
                    handler(resolve,reject)
                }catch{
                    reject(error)
                }
            }
            promiseResultProduce(promise2,val,resolve,reject){
                if(val instanceof myPromise){
    
                }else if((typeof val === 'object' || typeof val === 'function')){
                    if(typeof val.then === 'function'){
    
                    }else{
                        resolve(val)
                    }
                }else{
                    resolve(val)
                }
            }
            then(onResolve=val=>val,onReject){
                if(this.status === PENDDING){
                    const promise2 = new myPromise((resolve,reject)=>{
                        this.resolveCallback.push(()=>{
                            let val = onResolve(this.value)
                            setTimeout(()=>{
                                this.promiseResultProduce(promise2,val,resolve,reject)
                            },0)
                        })
                    })
                    return promise2
                }
                if(this.status === RESOLVED){
                    const promise2 = new myPromise((resolve,reject)=>{
                        let val = onResolve(this.value)
                        setTimeout(()=>{
                            this.promiseResultProduce(promise2,val,resolve,reject)
                        },0)
                    })
                    return promise2
                }
                if(this.status === REJECTED){
                    onReject(this.reason)
                }
            }
        }
        
        new myPromise((resolve)=>{
            setTimeout(()=>{
                resolve(123)
            },2000)
        }).then((res)=>res)
        .then((res)=>{
            console.log(res)
            return res
        }).then((res)=>{
            console.log(res)
        })
    

    3 实现 支持promise对象

        const PENDDING = 'pendding',
        RESOLVED = 'resolved',
        REJECTED = 'rejected'
        class myPromise {
            constructor(handler){
                this.status = PENDDING
                this.value = undefined
                this.resolveCallback = []
                this.rejectCallback = []
                let resolve = (value)=>{
                    if(this.status === PENDDING){
                        this.status = RESOLVED
                        this.value = value
                        this.resolveCallback.forEach((cb)=>{
                            cb()
                        })
                    }
                }
                let reject = (error)=>{
                    if(this.status === PENDDING){
                        this.status = REJECTED
                        this.reason = error
                        this.rejectCallback.forEach((cb)=>{
                            cb()
                        })
                    }
                }
                try{
                    handler(resolve,reject)
                }catch{
                    reject(error)
                }
            }
            promiseResultProduce(promise2,val,resolve,reject){
                if(val instanceof myPromise){
                    if(val.status === PENDDING){
                        console.log(222)
                        val.then(y=>{
                            console.log(y)
                            this.promiseResultProduce(promise2,y,resolve,reject)
                        },reject)
                    }else{
                        /*注意此时val是promise自然有this.value,this.status,this.reason属性*/
                        val.status === RESOLVED && resolve(val.value)
                        val.status === REJECTED && reject(val.reason)
                    }
                } else if((typeof val === 'object' || typeof val === 'function')){
    
                } else{
                    console.log(1111)
                    resolve(val)
                }
            }
            then(onResolve=val=>val,onReject){
                if(this.status === PENDDING){
                    const promise2 = new myPromise((resolve,reject)=>{
                        this.resolveCallback.push(()=>{
                            let val = onResolve(this.value)
                            setTimeout(()=>{
                                this.promiseResultProduce(promise2,val,resolve,reject)
                            },0)
                        })
                    })
                    return promise2
                }
                if(this.status === RESOLVED){
                    const promise2 = new myPromise((resolve,reject)=>{
                        let val = onResolve(this.value)
                        this.resolveCallback.push(()=>{
                            setTimeout(()=>{
                                this.promiseResultProduce(promise2,val,resolve,reject)
                            },0)
                        })
                    })
                    return promise2
                }
                if(this.status === REJECTED){
                    onReject(this.reason)
                }
            }
        }
    
        new myPromise((resolve)=>{
            setTimeout(()=>{
                resolve(123)
            },2000)
        })
        .then((res)=>{
            console.log(res)
            return new myPromise((resolve,reject)=>{
                setTimeout(()=>{
                    resolve(666)
                },2000)
            })
        })
        .then((res)=>{
            console.log(res)
        })
    

    4支持thenable对象

        const PENDDING = 'pendding',
        RESOLVED = 'resolved',
        REJECTED = 'rejected'
        class myPromise {
            constructor(handler){
                this.status = PENDDING
                this.value = undefined
                this.resolveCallback = []
                this.rejectCallback = []
                let resolve = (value)=>{
                    if(this.status === PENDDING){
                        this.status = RESOLVED
                        this.value = value
                        this.resolveCallback.forEach((cb)=>{
                            cb()
                        })
                    }
                }
                let reject = (error)=>{
                    if(this.status === PENDDING){
                        this.status = REJECTED
                        this.reason = error
                        this.rejectCallback.forEach((cb)=>{
                            cb()
                        })
                    }
                }
                try{
                    handler(resolve,reject)
                }catch{
                    reject(error)
                }
            }
            promiseResultProduce(promise2,val,resolve,reject){
                if(val instanceof myPromise){
                    if(val.status === PENDDING){
                        val.then(y=>{
                            this.promiseResultProduce(promise2,y,resolve,reject)
                        },reject)
                    }else{
                        /*注意此时val是promise自然有this.value,this.status,this.reason属性*/
                        val.status === RESOLVED && resolve(val.value)
                        val.status === REJECTED && reject(val.reason)
                    }
                } else if((typeof val === 'object' || typeof val === 'function')){
                    if(typeof val.then === 'function'){
                        val.then(y=>{
                            this.promiseResultProduce(promise2,y,resolve,reject)
                        },reject)
                    }else{
                        resolve(val)
                    }
                } else{
                    resolve(val)
                }
            }
            then(onResolve=val=>val,onReject){
                if(this.status === PENDDING){
                    const promise2 = new myPromise((resolve,reject)=>{
                        this.resolveCallback.push(()=>{
                            let val = onResolve(this.value)
                            setTimeout(()=>{
                                this.promiseResultProduce(promise2,val,resolve,reject)
                            },0)
                        })
                    })
                    return promise2
                }
                if(this.status === RESOLVED){
                    const promise2 = new myPromise((resolve,reject)=>{
                        let val = onResolve(this.value)
                        this.resolveCallback.push(()=>{
                            setTimeout(()=>{
                                this.promiseResultProduce(promise2,val,resolve,reject)
                            },0)
                        })
                    })
                    return promise2
                }
                if(this.status === REJECTED){
                    onReject(this.reason)
                }
            }
        }
        // 支持thenable对象
        // let result = {
        //     then(r){
        //         r(444)
        //     }
        // }
        // result.then(y=>{
        //     console.log(y)
        // })
    
        /*穿透的原理*/
        // new myPromise((resolve)=>{
        //     setTimeout(()=>{
        //         resolve(123)
        //     },2000)
        // }).then((res)=>res).then((res)=>{
        //     console.log(res)
        // })
    	
    	Promise.allSettled = function(param){
    		let result = []
    		let count = 0
    		let ln = param.length
    		return new Promise((resolve,reject)=>{
    			for(let task of param){
    				Promise.resolve(task).then((res)=>{
    					result[count] = {value:res,status:'fulfilled'};
    					++count === ln && resolve(result)
    				}).catch((err)=>{
    					result[count] = {reason:err,status:'rejected'};
    					++count === ln && resolve(result)
    				})
    			}
    		})
    	}
    	const test2 = 'test2'
    	const test3 = ()=>{
    		return new Promise((resolve,reject)=>{
    			setTimeout(()=>{
    				reject('err')
    			},1000)
    		})
    	}
    	Promise.allSettled([test2,test3()]).then((res)=>{
    		console.log(res)
    	})
    
  • 相关阅读:
    我爱java系列之---【微服务间的认证—Feign拦截器】
    我爱java系列之---【设置权限的三种解决方案】
    581. Shortest Unsorted Continuous Subarray
    129. Sum Root to Leaf Numbers
    513. Find Bottom Left Tree Value
    515. Find Largest Value in Each Tree Row
    155. Min Stack max stack Maxpop O(1) 操作
    painting house
    Minimum Adjustment Cost
    k Sum
  • 原文地址:https://www.cnblogs.com/MDGE/p/14839460.html
Copyright © 2011-2022 走看看