Please enable JavaScript to use CodeHS

Asynchronous Input

Get input in JavaScript programs without the popup!

By Andy Bayer

Software Developer at CodeHS

Non-Blocking Input in JavaScript Programs

One of the unique things about running JavaScript in CodeHS is “blocking input.” Blocking input refers to input (like readLine, readInt, etc.) that “block” the execution of the program until they receive an input. These are sometimes called “synchronous” functions, which means they need to happen immediately before the program can continue.

What’s more, output from previous lines cannot be written to the console until the blocking readLine call is complete. The entire browser has to wait for prompt to close, which means it’s unable to display output.

This often happens with graphical programs, as well. When code blocks it prevents any graphics from being drawn to the canvas. You can see that in the following program:

Asynchronous Input

JavaScript has several mechanisms for solving this, all of which are versions of “asynchronous” functions. Asynchronous functions are different than our blocking, synchronous functions. These functions allow the browser to continue executing while they wait to receive input, sometimes referred to as “yielding.”

We’re introducing several functions for doing asynchronous input: readLineAsync, readIntAsync, readBooleanAsync, and readFloatAsync. These functions work similarly to the ones you may be familiar with, but they yield execution to the browser while they wait for input.

To use these functions, you’ll want to use a special reserved word await. This reserved word will cause the program to wait for input before continuing, but without blocking the entire browser.

This program will await the result of readLineAsync on line 2, but while it’s waiting you’re able to edit your code, scroll around, switch tabs, whatever you want! To give input to these asynchronous functions, you’ll need to click the console, type your input, then hit enter.

You can try the same with graphical programs, which you can interact with even while your program is waiting for input.

Using await

A final note is that if you want to use the await keyword in a function, that function will need to be marked as an asynchronous function so that JavaScript knows it might have to wait for it.

You can do this with the async keyword:

async function askForAge() {
    let age = await readInt("How old are you? ");
}

askForAge();
JavaScript

Using an asynchronous value

To use the value from an asynchronous function in your program, you can assign it to a variable, just like with readInt etc.

let name = await readLineAsync("What's your name? ");
println("Nice to meet you, " + name);
JavaScript