Home > Enterprise >  Await a variable from an event
Await a variable from an event

Time:10-16

Update: I followed the first answer and here is my final code

// My Class Function
WaitFor(eventName) {
    return new Promise((resolve) => 
    {
        const handler = (value) => { resolve(value); };
        this.on(eventName, handler);
    });
}



// My index.js
var Console = require("./Console.js");
(async () =>
{
    var input = await Console.WaitFor('input');
    console.log(input);
})();

I am trying to code an interactive interface, for that i listen to key inputs with readline & process.stdin inside a class. My code right now is

Console.on('input', (input) => {
    console.log(input); // Return a key Input
    process.exit(0)
})

What i would like to be able to do is listen to the event exceptionally in an await. So i can define variable on the spot by waiting for the next user input . Example:

var input = await event(Console, 'input');
console.log(input);
/* 
   event on this case would be a custom functions suggested since i don't know how
   i could do that properly . . .
*/

Is there a way to do that somehow ? Please let me know if my question is not

CodePudding user response:

Assuming you have an off to go with your on method, yes, event could look like this:

function event(source, eventName) {
    return new Promise((resolve) => {
        const handler = (value) => {
            resolve(value);
            source.off(eventName, handler);
        };
        source.on(eventName, handler);
    });
}

That creates a promise and subscribes to the event. The next time the event occurs, the handler fulfills the promise with any value it receives (that part is optional) and unsubscribes from the event.

  • Related