Search code examples
javascriptblocking

How to block for input in javascript


Conceptually what I need to do in javascript is the following:

// A) set up stuff

// B) collect values from input
do {
    var key = readKey();
    // do stuff like loading arrays, objects, etc based on this sequential input
} while (key != '.') // period signifies completion

// C) continue to do other stuff that can only be done once the arrays and objects from before are completely loaded.

I know that IO is non-blocking in javascript. So I have tried setting keyboard listeners and looping in a setTimeout construct, but I cannot avoid program execution flying through to C) and error-ing out because all of the prerequisite processing that is part of B) is not complete.

Here is what I tried:

// A) prepare stuff
var digrams = type() // B
// C) deal with digrams (errors out if digrams not complete)

function type() {
  var loopid;

  var loop = function() {
    // NOP
  };

  document.onkeypress = function (e) {
    e = e || window.event;
    var char = String.fromCharCode(e.keyCode);
    ...
    if (char=='.') {
     document.onkeypress = null;
     clearInterval(loopid);
     return digrams; // arr of obj composed thru key input
    }
  } // keylistener

  // Start the type loop
  loopid = setInterval( loop, 10);
}   

I really need a way to work "against" javascript here. Any example code would be appreciated.


Solution

  • You can use Promise, to return a value asynchronously to .then()

    // A) prepare stuff
    var digrams = type();
    digrams
    .then(funcion handleSuccess(value) {
      // do stuff with `value` : `arr` passed to `resolve()`
    }
    , function handleError(err) {
      // handle error
    }); // B
    // C) deal with digrams (errors out if digrams not complete)
    
    function type() {
      return new Promise(function(resolve, reject) {
        var loopid;
    
        var loop = function() {
          // NOP
        };
    
        document.onkeypress = function (e) {
          e = e || window.event;
          var char = String.fromCharCode(e.keyCode);
          ...
          if (char=='.') {
            document.onkeypress = null;
            clearInterval(loopid);
            resolve(arr);
            // return digrams; // arr of obj composed thru key input
          }
          // reject(new Error("error message"));
        } // keylistener
    
        // Start the type loop
        loopid = setInterval( loop, 10);
      });
    }