解决异步的方案---回调函数

异步需要注意的问题

  • 异步没法捕获错误,异步代码不能try catch捕获
  • 异步编程中可能出现回调地狱
  • 多个异步的操作 在同一个时间内容 同步异步的结果

高阶函数

  • 函数作为函数的参数
  • 函数执行结果返回函数

after函数(在xxx之后执行,可以限制达到多少次后执行此回调)

    function after(times,cb){
        return function(){
            if(--times==0){
                cb()
            }
        }
    }
    
    let fn = after(3,function(){
        console.log('达到三次了')
    })
    
    fn()
    fn()
    fn()
复制代码

node文件操作

需要name和age都获取到然后输出。

    let fs = require('fs')
    let schoolInfo = {}
    function after(times,cb){
        return function(){
            if(--times==0){
                cb()
            }
        }
    }
    let fn = after(2,function(){
        consolr.log(schoolInfo)
    })
    fs.readFile('./name.txt','utf8',function(err,data){
        schoolInfo['name'] = data;
        fn()
    })
    
    fs.readFile('./age.txt','utf8',function(err,data){
       schoolInfo['age'] = data;
       fn()
    })
复制代码

发布订阅

    let dep = {
        arr:[],
        emit(){
            this.arr.forEach(fn=>fn())
        }
        on(fn){
            this.arr.push(fn)
        }
    }
    dep.on(function(){
        if(Object.keys(schoolInfo).length===2){
            console.log(schoolInfo)
        }
    })
    fs.readFile('./name.txt','utf8',function(err,data){
        schoolInfo['name'] = data;
        dep.emit()
    })
    
    fs.readFile('./age.txt','utf8',function(err,data){
       schoolInfo['age'] = data;
       dep.emit()
    })
复制代码

猜你喜欢

转载自juejin.im/post/5c59964b51882562e17c05cd