Asynchrony concerns

  • Asynchronous code cannot catch errors. Asynchronous code cannot try catch
  • Callback hell can occur in asynchronous programming
  • The result of asynchronous content synchronization for multiple asynchronous operations at the same time

Higher-order functions

  • Functions as arguments to functions
  • Function returns the result of its execution

The after function (executed after XXX, you can limit how many times this callback can be executed)

    function after(times,cb){
        return function() {if(--times==0){
                cb()
            }
        }
    }
    
    let fn = after(3,function(){
        console.log('Three times.')
    })
    
    fn()
    fn()
    fn()
Copy the code

The function is currified

Function corrification is the ability to divide the parameters passed by a function into multiple executions

Const add = (a, b, c, d, e) => {// 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] [2,3] < 5if(arr.length < len){
                return curring(fn,arr)
            }
            returnfn(... arr) } }letr = curring(add)(1)(2)(3)(4); / / [1, 2, 3, 4, 5]Copy the code

Simple use to determine the data type

    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); // Pass in an argument}); console.log(utils.isString('hello'));
Copy the code

Node file Operations

We need to get both name and age and print it.

    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()
    })
Copy the code

Release subscription

    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()
    })
Copy the code