Reputation:
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
Upvotes: 2
Views: 307
Reputation:
Using the previous answer here is my final code
WaitFor(eventName)
{
return new Promise((resolve) =>
{
this.on('disconnect', () => {
resolve(null); // Got disconnected from WebSocket, so we cancell the user input
});
this.on(eventName, (value) => {
resolve(value); // Got the event called
});
});
}
Example of use:
var licenseKey = await Console.WaitFor('input');
console.log(await licenseKey);
Upvotes: 0
Reputation: 1074168
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.
Upvotes: 2