编写自己的事件发射器失败



我正在尝试基于此地形编写一个事件发射器。但是最后一个事件on('cooked')没有触发,为什么?

var events = require('events');
function Dummy() {
    events.EventEmitter.call(this);
}
Dummy.super_ = events.EventEmitter;
Dummy.prototype = Object.create(events.EventEmitter.prototype, {
    constructor: {
        value: Dummy,
        enumerable: false
    }
});
function _cook(a,cb) {
    console.log('frying it',a)
    cb(a)
}
Dummy.prototype.cooking = function(chicken) {
    var self = this;
    self.chicken = chicken;
    self.cook = _cook; // assume dummy function that'll do the cooking
    self.cook(chicken, function(cooked_chicken) {
        console.log('callback')
        self.chicken = cooked_chicken;
        self.emit('cooked', self.chicken);
    });
    return self;
}
var kenny = new Dummy();
fried_chix = {type:'tasty'}
var dinner = kenny.cooking(fried_chix);
dinner.on('cooked', function(chicken) {
    console.log('we can eat now!')
})

问题是你的整个代码是同步的。

作为调用 kenny.cooking() 的一部分,将发出 cooked 事件(同步),但此时尚未为该事件附加侦听器。

如果使_cook方法异步,它将起作用:

function _cook(a,cb) {
  console.log('frying it',a)
  setImmediate(function() {
    cb(a);
  });
}

最新更新