gpt4 book ai didi

javascript - 如何创建一个等待 Javascript 事件的异步函数?

转载 作者:搜寻专家 更新时间:2023-10-31 23:44:30 25 4
gpt4 key购买 nike

如何阻止事件?

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
做某事
做某事
做某事
做某事

最佳答案

如果我正确理解你的问题,那么这可以通过包装 task 事件处理程序的 Promise 来实现:

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 处理程序,以便在事件处理程序触发后调用 promise resolve (即通过调用 解决())。这允许恢复对 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() 函数后,您可以使用与 do_work() 相关的 await 来强制执行 task.run(5)do_work() 完成后。

希望这对您有所帮助!

关于javascript - 如何创建一个等待 Javascript 事件的异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53900575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com