osric.uk

nextKey needs to set the keypress handler for target. The handler needs to pass a value back to nextkey, so next key can yield that value to it's caller.

Handler can pass a value to nextKey with a promise. nextKey creates a promise in a variable shared with handler, and then awaits it. Handler gets a key and resolves the promise. nextKey yields the value from the promise, and them loops to reinitialize the promise.


async function* nextKey(target) {
  let sharedPromise;

  function handler(e) {
    sharedPromise.resolve(e);
  }

  target.addEventListener("keypress", handler);

  while (true) {
    sharedPromise = new Promise();    
    yield await sharedPromise;
  }
}