发布订阅模式Pub/Sub

2019-08-06  本文已影响0人  TerdShow
let fs = require('fs');
let man = {};

class Events {
  constructor() {
    this.stack = [];
  }
  on(callback) {
    this.stack.push(callback);
  }
  emit() {
    this.stack.forEach(callback => callback());
  }
}

let events = new Events();

events.on(()=>{
  console.log('done');
});
events.on(() => {
  if(Object.keys(man).length === 2) {
    console.log('finish');
  }
})

fs.readFile('./name.txt', 'utf8', function(err, data){
  man.name = data;
  events.emit();
})

fs.readFile('./age.txt', 'utf8', function(err, data){
  man.age = data;
  events.emit();
})
上一篇 下一篇

猜你喜欢

热点阅读