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

异步须要注意的问题

  • 异步无法捕获错误,异步代码不能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

// 通用的柯里化
    const add = (a, b, c, d, e) => {
       return a + b + c + d + e;
    };
    const curring = (fn,arr = [])=>{
        let len = fn.length
        return (...args)=>{
            arr = arr.concat(args); // [1]  [1,2,3] < 5
            if(arr.length < len){
                return curring(fn,arr)
            }
            return fn(...arr)
        }
    }
    let r = curring(add)(1)(2)(3)(4); // [1,2,3,4,5]
复制代码

简单使用判断数据类型编程

const checkType = (type, content) => {
        return Object.prototype.toString.call(content) === `[object ${type}]`;
    };
    let types = ["Number", "String", "Boolean"];
    let utils = {};
    types.forEach(type => {
      utils["is" + type] = curring(checkType)(type); // 先传入一个参数
    });
    console.log(utils.isString('hello'));
复制代码

node文件操做

须要name和age都获取到而后输出。bash

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()
    })
复制代码
相关文章
相关标签/搜索