Search code examples
javascriptdom-events

Javascript promise resolved by keyboard event


I am trying to target the keyboard event to resolve my promise, but it's not working anymore.

The function below is to compare the key I give it in the param with the one the user typed:

function compareKey(a, b) {


if (a && b) {
    (a == b) ? output("it matched"): output("it did not match");
}
}

The following function is to execute the compareKey function right after the user typed a key:

function KeyCatcher(a, ck) {

var touche = null;
document.addEventListener("keydown", function(ev) {

    if (ev) {
        touche = ev.key;
    }

})
    if (touche != null) {
       ck(a, touche);
    }
}

Here I declare a promise that will help me wait for the keyboard event:

var keyBoardEventCatch = function(a) {
output("promise");
return new Promise(function(resolve) {
    KeyCatcher(a, resolve);
});
}

var whenRandom = keyBoardEventCatch('a');

Here is where I execute the promise:

whenRandom
.then(compareKey);


function output(a) {
console.log(a);
}

Solution

  • With the way you have written it, the resolve function is never called. Look at your KeyCatcher function. You are adding an event listener and passing a function to be called at the time the event happens. Everything outside of that callback functions is executed immediately, including

    if (touche != null) {
      ck (a, touche);
    }
    

    At this point, touche will always be null, as the callback function hasn't been called yet. to fix this, move that block of code into your callback function.

    Your next issue comes with passing the captured key to compareKey function. Resolve only accepts one argument, so you need to alter your input. Pass an object or an array if you want to send multiple variables.