Node学习笔记(十四)—— Promise | Async

写法不同
  1. ES5正常的写法
    getAjax(url,(res)=>{})
    
  2. Promise写法
    getAjax(url).then((res)=>{})
    
  3. Async写法
    // 异步async函数调用后也是一个Promise对象
    (async ()=>{
        let res=await getAjax(url) 
    })()
    
    总结:ES5写法会造成回调地狱,代码可读性差;Promise写法让回调函数划分出去,避免了函数回调地狱,提高代码可读性;Async写法是Promise的语法糖,使得代码回归正常,阅读性高,更加简洁,底层编译会自动转换为Promise的写法
Promise实现原理
  1. 定义一个类

    class Promise{
    	// 定义构造函数
        constructor(fn){
            // 成功事件集成在successList数组里
            this.successList=[]
            // 失败事件集成在failList数组里
            this.failList=[]
            // 定义状态
            this.state='pending'
            // 传入的函数对象(异步操作的函数内容)
            fn(this.resolveFn.bind(this),this.rejectFn.bind(this))
    
        }
        // 2. 传入成功或者失败时执行的函数
        then(successFn,failFn){
            if(typeof successFn=='function'){
                this.successList.push(successFn)
            }
            if(typeof failFn=='function'){
                this.failList.push(failFn)
            }
        }
        catch(failFn){
            if(typeof failFn=='function'){
                this.failList.push(failFn)
            }
        }
        // 定义调用成功和失败的函数
        resolveFn(res){
            this.state='fullfilled'
            // 调用成功后的事件
            this.successList.forEach((item,index)={
                item(res)
            })
        }
        rejectFn(res){
            this.state='rejected'
            // 调用失败后的事件
            this.failList.forEach((item,index)={
                item(res)
            })
            throw Error(res)
        }
    }
    
  2. 应用

    function fsRead(path){
        return new Promise(function(resolve,reject){
            fs.readFile(path,{flag:'r',encoding:'utf-8'},(err,data)=>{
                if(err){
                    reject(err)
                }else{
                    resolve(data)
                }  
            })
        })
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值