I have problem implementing await inside event handler. For some reason, event handler doesn't wait for first process to finish before starting new one. Why is this weird behaviour so?
const { EventEmitter } = require("events");
let alreadyRunning = false;
const sampleEventHandler = new EventEmitter();
sampleEventHandler.on("data", async (message) => {
await heavyProcess(message);
});
async function heavyProcess(message) {
console.log("New message: ", message);
console.log("already running?: ", alreadyRunning);
if (alreadyRunning) {
console.log("Why doesn't it await for first task to complete fully before entering here?");
}
const rand = Math.random() * 1000;
// set var here
alreadyRunning = true;
await sleep(rand);
// unset here
alreadyRunning = false;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Emit event 5 times
for (let i = 0; i < 5; i++) {
sampleEventHandler.emit("data", i);
}
You need to promisify heavyProcess
function in order to using await with it successfuly:
function heavyProcess(message) {
return new Promise( async (resolve, reject) => {
console.log("New message: ", message);
console.log("already running?: ", alreadyRunning);
if (alreadyRunning) {
console.log("Why doesn't it await for first task to complete fully before entering here?");
}
const rand = Math.random() * 1000;
// set var here
alreadyRunning = true;
await sleep(rand);
// unset here
alreadyRunning = false;
resolve('Done');
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With