如何阻止该事件?
const EventEmitter = require('events').EventEmitter;
const util = require('util');
function Task() {
EventEmitter.call(this);
this.setMaxListeners(Infinity);
this.dosomething = () => {
console.log("do something");
};
this.run = (iter) => {
for(i = 0; i < iter; i++) {
this.dosomething();
this.emit('someevent');
}
}
}
util.inherits(Task, EventEmitter);
task = new Task();
function do_work() {
console.log("work 1");
task.once('someevent', (props) => {
console.log('event happened');
});
console.log("work 2");
}
do_work();
task.run(5);
实际结果
工作1
工作2
做某事
事件发生
某
事做某事
某
事做某事某事
预期结果
工作1
做某事
事件发生
工作2
做某事
做某事
做某事
做某事
如果我正确理解了您的问题,则可以通过Promise
包装task
事件处理程序的a来实现:
async function do_work() {
console.log("work 1");
// use a promise to block completion of do_work() function
// until task event callback has been invoked
await (new Promise(resolve => {
task.once('someevent', (props) => {
console.log('event happened');
// Now that task callback has been invoked, "resolve" the
// enclosing promise to allow do_work()'s execution to complete
resolve();
});
}));
console.log("work 2");
}
上面代码中的想法是包装任务someevent
处理程序,以便resolve
一旦事件处理程序触发(即通过调用resolve()
)就可以调用promise 。这允许继续调用do_work()
,以实现所需的执行行为。
另外,您将需要执行以下操作:
// Because do_work() is async, and becase you want to ensure that
// do_work() completes before starting task.run(5), you need to enclose
// these in an async function, eg doWorkThenRunTasks()
async function doWorkThenRunTasks() {
// Call do_work asynchronously
await do_work()
// task.run will happen after do_work completed
task.run(5);
}
doWorkThenRunTasks();
加入异步的doWorkThenRunTasks()
功能,允许你使用await
有关do_work()
强制执行的执行顺序task.run(5)
完成后do_work()
。
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句