Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Await a variable from an event

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading