异步需要注意的问题
异步没法捕获错误, 异步代码不能 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()
- })
来源: https://juejin.im/post/5c59964b51882562e17c05cd