我喜欢像folloiwng这样的模块,我想发出像下面这样的事件
档案 aa.js
var EventEmitter = require("events").EventEmitter,
eventEmitterIns = new EventEmitter();
var preProcess = function (cb) {
...
var start = function () {
....
}).catch(function (err) {
//-------------HERE I EMIT THE EVENT-----------
eventEmitterIns.emit('test');
}
}
}
module.exports = {
preProcess: preProcess,
eventEmitterIns: eventEmitterIns
};
现在我想在其他模块中捕获此错误事件,当我执行以下操作时它对我不起作用
bb.js
var invokeAppEvents = require('../controller/aa');
invokeAppEvents.eventEmitterIns.on('test', function () {
debugger;
}
);
如果我放断点它在调试器中没有停止,我怎么能克服这个?
调用catch块中的代码!
我应该在aa.js中导出什么以及我应该在bb.js中要求什么?
答案 0 :(得分:0)
您必须致电preProcess()
和内部start()
功能才能举办活动。例如:
<强> aa.js 强>
var EventEmitter = require("events").EventEmitter;
var eventEmitterIns = new EventEmitter();
var preProcess = function (cb) {
var start = function () {
Promise.reject('error...')
.catch(function (err) {
eventEmitterIns.emit('test', err);
});
}
start(); // << start() be must called somewhere
}
module.exports = {
preProcess: preProcess,
eventEmitterIns: eventEmitterIns
};
<强> bb.js 强>
var invokeAppEvents = require('./aa');
// preProcess() must be called so start() can run
invokeAppEvents.preProcess();
invokeAppEvents.eventEmitterIns.on('test', function (data) {
console.log('test event received: ' + data);
});
正如预期的那样,输出:
收到的测试事件:错误......