解決非同步的方案---回撥函式
摘要:
非同步沒法捕獲錯誤,非同步程式碼不能try catch捕獲
非同步程式設計中可能出現回撥地獄
多個非同步的操作 在同一個時間內容 同步非同步的結果
高階函式
函式作為函式的引數
函式執行結果返回函式
after函式(在xxx之...
- 非同步沒法捕獲錯誤,非同步程式碼不能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() }) 複製程式碼