0

I'm porting some BASIC programs to Javascript, and I need an INPUT-like statement. My output "console" is a pre id="output" HTML element. I'm adding the output as text nodes inside the pre element.

My INPUT-like routine adds a input type="text" length="50" element to the output, and should wait for the text from the user until Enter key is pressed, and then the input element is removed. Supposedly I read the Promise definition in Mozilla, saw tons of related examples, but now I'm four hours and counting on this, and I'm feeling like I hit my head on the wall.

Even put the promise in an async function and used return await new Promise, etc, ect.

What I'm doing wrong? Tested with Firefox 78.7.1

function print(str)
{
    document.getElementById("output").appendChild(document.createTextNode(str));
}

function input()
{
    var input_element = document.createElement("INPUT");
    var promise;
    var input_str;

    print("? ");
    input_element.setAttribute("type", "text");
    input_element.setAttribute("length", "50");
    document.getElementById("output").appendChild(input_element);
    input_str = undefined;
    new Promise(function (resolve) {
        input_element.addEventListener("keydown", function (event) {
            if (event.keyCode == 13) 
                resolve(input_element.value);
        });
    }).then(function (str) { input_str = str; });
    document.getElementById("output").removeChild(input_element);
    print(input_str);
    print("\n");
    return input_str;
}

The first answer helped me, but now I don't see how to return the string correctly. It always returns with input_str == undefined because doesn't wait for user to enter the string.

function input()
{
    var input_element;
    var input_str;

    new Promise(function (resolve) {
        input_element = document.createElement("INPUT");

        print("? ");
        input_element.setAttribute("type", "text");
        input_element.setAttribute("length", "50");
        document.getElementById("output").appendChild(input_element);
        input_str = undefined;
        input_element.addEventListener("keydown", function (event) {
            if (event.keyCode == 13) 
                resolve(input_element.value);
        });
    }).then(function (str) {
        input_str = str;
        document.getElementById("output").removeChild(input_element);
        print(input_str);
        print("\n");
    });
    return input_str;
}

EDIT: Finally understood it, the Promise is a kind of subthread that runs in their own, same for async functions. So what I did (with help of @kuvos) after grasping the concept, was to create an async function main() to contain the whole BASIC code and call input function using a = await input(). You can see the final code at https://github.com/nanochess/basic-computer-games/tree/main/03%20Animal/javascript

nanochess
  • 1
  • 2

0 Answers0