Is there a way to write async await code that responds to onkeypress events?
Yes. Let's break it down:
Is it possible to await a custom thing?
Yes — you can await any Promise
. For example, to wait for a timeout:
const timerPromise = new Promise(resolve => setTimeout(resolve, 1000));
await timerPromise;
Is it possible to have a promise for a key press?
Yes — resolve the promise when an event happens.
function readKey() {
return new Promise(resolve => {
window.addEventListener('keypress', resolve, {once:true});
});
}
Thanks to @Kornel and @Xotic750, here's what I was looking for:
const readKey = () => new Promise(resolve => window.addEventListener('keypress', resolve, { once: true }));
(async function() {
console.log('Press a key');
const x = await readKey();
console.log('Pressed', String.fromCharCode(x.which));
console.log('Press a key');
const y = await readKey();
console.log('Pressed', String.fromCharCode(y.which));
}());