JavaScript 48 · Build an Asynchronous Radio Briefing

JavaScript lesson 48 of 50 · Expert projects · About 35 minutes

Let Pip receive a delayed message while the rest of the game keeps running.

Pip watches six little cloud creatures gather safely in the glow of the restored wind beacon at dawn.
Mission Use a Promise and async/await to handle a simulated radio response.

Get ready

Open Complete checkpoint below. For a browser preview, put the HTML in your editor’s HTML panel and the JavaScript in its JavaScript panel. For a local file, put the HTML first in a new .html file, then put the JavaScript between <script> and </script> at the end. Save the file and open it in a browser.

Match the HTML to the JavaScript. HTML tags create the game’s controls and text. An id names one element. The code uses that name to find the element. A class groups elements for styling, while a data- attribute can carry a game value. A status area with aria-live lets compatible screen readers announce updates.

Request. Start the simulated radio call. → Wait. Leave the controls available. → Deliver. Show a message only for the current mission.
Request → Wait → Deliver

Understand the JavaScript in this lesson

Language to look for Promise, setTimeout, async/await, finally, Object identity.

1. Respond with a promise

A promise represents a result that may arrive later. new Promise calls the function you pass it. That function receives resolve, which provides the successful result. setTimeout asks the browser to run a callback after a delay of at least 450 milliseconds. When the callback runs, resolve gives the promise a message about the mission. This simulation runs entirely in the page.

return new Promise(resolve => {

2. Wait for the message

The async keyword allows the click handler to use await. The handler starts by disabling the briefing button and reporting that it is waiting. When it reaches await, it pauses this handler until the promise settles. Other events such as clicking East can still run. When the promise resolves, message receives its text and the handler continues.

const message = await getBriefing(requestedMission);

3. Keep messages attached to a run

The handler keeps a reference to the mission object it requested. Restart copies the mission into a fresh object. When the promise resolves, comparing references with === catches a restart even if the seed has the same value. If the mission has changed, the old response is no longer needed and the handler can leave the new run's message alone.

if (requestedMission === mission) log.textContent = message;

4. Clean up after each request

If the promise rejects, await throws and catch can report the problem. The supplied simulator always resolves, so the error path is there for a changed simulator that can fail. finally executes after either success or error and reenables the button. Grab event.currentTarget before awaiting because it refers to the button only while the event is being dispatched.

button.disabled = false;
Follow what happens step by step
  1. Listen to the briefing, then press East
    Pip moves while the radio waitsWhy Only the async handler pauses at await.
  2. Listen again and restart quickly
    Old mission message is skippedWhy Restart replaces the mission object before the old promise finishes.

Predict before you run What does await do to the rest of the page while Pip's briefing is pending?

Reveal the answer

Other handlers can keep running. Only the briefing handler waits for this promise.

Complete checkpoint

HTML · the page and controls

<section id="board" tabindex="0" role="region" aria-label="Pip's rover controls" aria-describedby="how">
  <p id="how">Use the direction buttons. Tab to this panel to use arrow keys.</p>
  <p id="status" role="status" aria-atomic="true"></p>
  <button type="button" data-move="north">North</button>
  <button type="button" data-move="east">East</button>
  <button type="button" data-move="south">South</button>
  <button type="button" data-move="west">West</button>
</section>
<p id="log" role="status" aria-atomic="true"></p>
<button type="button" id="restart">Restart mission</button>
<button type="button" id="brief">Listen to the briefing</button>

JavaScript · the instructions

const links = {
  dock: { east: "workshop", south: "garden" },
  workshop: { west: "dock", south: "beacon" },
  garden: { north: "dock", east: "beacon" },
  beacon: { north: "workshop", west: "garden" }
};
const directions = ["north", "east", "south", "west"];
const standard = {
  seed: 1, capacity: 6,
  pickup: { workshop: 1, garden: 2 }
};
const newRun = mission => ({
  room: "dock", energy: mission.capacity, parts: 0, rescued: false
});
function step(state, command, mission) {
  if (state.rescued || state.energy === 0) return state;
  if (!directions.includes(command)) return state;
  const room = links[state.room][command];
  if (!room) return state;
  const parts = state.parts | (mission.pickup[room] ?? 0);
  return {
    room, parts,
    energy: room === "dock" ? mission.capacity : state.energy - 1,
    rescued: room === "beacon" && parts === 3
  };
}
function describe(state) {
  const names = { dock: "Sky Dock", workshop: "Workshop", garden: "Garden", beacon: "Beacon" };
  const pieces = ["none", "Cog", "Lens", "Cog + Lens"];
  const result = state.rescued ? " Cloud creatures rescued!" :
    state.energy === 0 ? " Battery empty. Restart to try again." : "";
  return names[state.room] + " | Energy " + state.energy +
    " | Parts: " + pieces[state.parts] + "." + result;
}

function makeMission(seed, capacity = 6) {
  const cleanSeed = seed >>> 0;
  const draw = (Math.imul(cleanSeed, 1664525) + 1013904223) >>> 0;
  const swap = draw >= 0x80000000;
  return {
    seed: cleanSeed, capacity,
    pickup: { workshop: swap ? 2 : 1, garden: swap ? 1 : 2 }
  };
}

const status = document.querySelector("#status");
const log = document.querySelector("#log");
let mission = makeMission(1);
let state;
let moves;
function render() {
  status.textContent = describe(state);
}
function startRun(nextMission) {
  mission = nextMission;
  state = newRun(mission);
  moves = [];
  log.textContent = "";
  render();
}
function move(command) {
  const next = step(state, command, mission);
  if (next === state) {
    log.textContent = "Pip stays put.";
    return;
  }
  moves.push(command);
  state = next;
  log.textContent = "";
  render();
}
for (const button of document.querySelectorAll("[data-move]")) {
  button.addEventListener("click", () => move(button.dataset.move));
}
document.querySelector("#restart").addEventListener("click", () => startRun({ ...mission }));
startRun(mission);

const arrow = new Map([
  ["ArrowUp", "north"], ["ArrowRight", "east"],
  ["ArrowDown", "south"], ["ArrowLeft", "west"]
]);
const board = document.querySelector("#board");
board.addEventListener("keydown", event => {
  const command = arrow.get(event.key);
  if (event.target !== board || event.altKey || event.ctrlKey ||
      event.metaKey || event.shiftKey || !command) return;
  event.preventDefault();
  if (!event.repeat) move(command);
});

function getBriefing(mission) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Mission " + mission.seed + ": Find the Cog and Lens, then reach the Beacon.");
    }, 450);
  });
}
document.querySelector("#brief").addEventListener("click", async event => {
  const button = event.currentTarget;
  const requestedMission = mission;
  button.disabled = true;
  log.textContent = "Waiting for the radio briefing…";
  try {
    const message = await getBriefing(requestedMission);
    if (requestedMission === mission) log.textContent = message;
  } catch (error) {
    if (requestedMission === mission) log.textContent = "Radio unavailable: " + error.message;
  } finally {
    button.disabled = false;
  }
});

Read the JavaScript line by line

Open a small group of lines while you read the complete checkpoint. Blank lines separate ideas. Closing braces mark the end of a block. An ellipsis here means you can read the rest in the full program.

Lines 1–19
Lines 1–6 const links = { dock: { east: "workshop", south: "garden" }, workshop: { west: "dock", south: "beacon" }, garden: { north: "dock", east: "beacon" }, beacon: { north: "workshop", west: "garden" } };
Set up links. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 7 const directions = ["north", "east", "south", "west"];
Set up directions. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Lines 8–11 const standard = { seed: 1, capacity: 6, pickup: { workshop: 1, garden: 2 } };
Set up standard. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Lines 12–14 const newRun = mission => ({ room: "dock", energy: mission.capacity, parts: 0, rescued: false });
Set up newRun. Keep this name attached to the same value. The arrow defines a function that this line can pass or save for later.
Line 15 function step(state, command, mission) {
Define step. The body runs when the function is called, with inputs named state, command, mission.
Line 16 if (state.rescued || state.energy === 0)
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The triple equals compares without converting the value’s type.
Line 16 return state;
Leave this function and send the value back to the caller.
Line 17 if (!directions.includes(command))
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test. Check whether the collection contains the supplied item or text.
Line 17 return state;
Leave this function and send the value back to the caller.
Line 18 const room = links[state.room][command];
Set up room. Keep this name attached to the same value. Work out what is inside the brackets first, then use it as the key or index.
Line 19 if (!room)
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 19 return state;
Leave this function and send the value back to the caller.
Lines 20–43
Line 20 const parts = state.parts | (mission.pickup[room] ?? 0);
Set up parts. Keep this name attached to the same value. Use the right side only when the left side is null or undefined. Work out what is inside the brackets first, then use it as the key or index.
Lines 21–25 return { room, parts, energy: room === "dock" ? mission.capacity : state.energy - 1, rescued: room === "beacon" && parts === 3 };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Line 27 function describe(state) {
Define describe. The body runs when the function is called, with inputs named state.
Line 28 const names = { dock: "Sky Dock", workshop: "Workshop", garden: "Garden", beacon: "Beacon" };
Set up names. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 29 const pieces = ["none", "Cog", "Lens", "Cog + Lens"];
Set up pieces. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Lines 30–31 const result = state.rescued ? " Cloud creatures rescued!" : state.energy === 0 ? " Battery empty. Restart to try again." : "";
Set up result. Keep this name attached to the same value. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Lines 32–33 return names[state.room] + " | Energy " + state.energy + " | Parts: " + pieces[state.parts] + "." + result;
Leave this function and send the value back to the caller. Plus adds numbers or joins text, depending on its values. Work out what is inside the brackets first, then use it as the key or index.
Line 36 function makeMission(seed, capacity = 6) {
Define makeMission. The body runs when the function is called, with inputs named seed, capacity = 6.
Line 37 const cleanSeed = seed >>> 0;
Set up cleanSeed. Keep this name attached to the same value. Shift the bits right and fill the spaces on the left with zeros.
Line 38 const draw = (Math.imul(cleanSeed, 1664525) + 1013904223) >>> 0;
Set up draw. Keep this name attached to the same value. Shift the bits right and fill the spaces on the left with zeros. Plus adds numbers or joins text, depending on its values.
Line 39 const swap = draw >= 0x80000000;
Set up swap. Keep this name attached to the same value. Check whether the first is greater than or equal to the second.
Lines 40–43 return { seed: cleanSeed, capacity, pickup: { workshop: swap ? 2 : 1, garden: swap ? 1 : 2 } };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Lines 46–58
Line 46 const status = document.querySelector("#status");
Set up status. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 47 const log = document.querySelector("#log");
Set up log. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 48 let mission = makeMission(1);
Set up mission. Give this name a starting value that later code can change. Call makeMission with the values inside the parentheses.
Line 49 let state;
Set up state. Give this name a starting value that later code can change.
Line 50 let moves;
Set up moves. Give this name a starting value that later code can change.
Line 51 function render() {
Define render. The body runs when the function is called.
Line 52 status.textContent = describe(state);
Call describe with the values inside the parentheses. Replace the element’s displayed text. The browser treats the value as text.
Line 54 function startRun(nextMission) {
Define startRun. The body runs when the function is called, with inputs named nextMission.
Line 55 mission = nextMission;
Store the result in the name or property to the left.
Line 56 state = newRun(mission);
Call newRun with the values inside the parentheses. Store the result in the name or property to the left.
Line 57 moves = [];
Square brackets create an ordered array. Its first position is 0. Store the result in the name or property to the left.
Line 58 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Lines 59–73
Line 59 render();
Call render with the values inside the parentheses.
Line 61 function move(command) {
Define move. The body runs when the function is called, with inputs named command.
Line 62 const next = step(state, command, mission);
Set up next. Keep this name attached to the same value. Call step with the values inside the parentheses.
Line 63 if (next === state) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 64 log.textContent = "Pip stays put.";
Replace the element’s displayed text. The browser treats the value as text.
Line 65 return;
Leave this function immediately.
Line 67 moves.push(command);
Add entries to the end of the array and return its new length.
Line 68 state = next;
Store the result in the name or property to the left.
Line 69 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Line 70 render();
Call render with the values inside the parentheses.
Line 72 for (const button of document.querySelectorAll("[data-move]")) {
Take one value at a time from this sequence and run the body with it.
Line 73 button.addEventListener("click", () => move(button.dataset.move));
Register a function the browser should call when the named event happens.
Lines 75–91
Line 75 document.querySelector("#restart").addEventListener("click", () => startRun({ ...mission }));
Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 76 startRun(mission);
Call startRun with the values inside the parentheses.
Lines 78–81 const arrow = new Map([ ["ArrowUp", "north"], ["ArrowRight", "east"], ["ArrowDown", "south"], ["ArrowLeft", "west"] ]);
Set up arrow. Keep this name attached to the same value. Use new to create a fresh Map object.
Line 82 const board = document.querySelector("#board");
Set up board. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 83 board.addEventListener("keydown", event => {
This function body is passed as an input. Register a function the browser should call when the named event happens.
Line 84 const command = arrow.get(event.key);
Set up command. Keep this name attached to the same value. Read the matching value from the collection.
Lines 85–86 if (event.target !== board || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || !command)
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation and two equals signs check whether values differ without type conversion.
Line 86 return;
Leave this function immediately.
Line 87 event.preventDefault();
Stop the browser’s usual response to this event where permitted.
Line 88 if (!event.repeat)
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 88 move(command);
Call move with the values inside the parentheses.
Line 91 function getBriefing(mission) {
Define getBriefing. The body runs when the function is called, with inputs named mission.
Lines 92–107
Lines 92–96 return new Promise(resolve => { setTimeout(() => { resolve("Mission " + mission.seed + ": Find the Cog and Lens, then reach the Beacon."); }, 450); });
Leave this function and send the value back to the caller. Use new to create a fresh Promise object.
Line 98 document.querySelector("#brief").addEventListener("click", async event => {
This function body is passed as an input. Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 99 const button = event.currentTarget;
Set up button. Keep this name attached to the same value.
Line 100 const requestedMission = mission;
Set up requestedMission. Keep this name attached to the same value.
Line 101 button.disabled = true;
Store the result in the name or property to the left.
Line 102 log.textContent = "Waiting for the radio briefing…";
Replace the element’s displayed text. The browser treats the value as text.
Line 103 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 104 const message = await getBriefing(requestedMission);
Set up message. Keep this name attached to the same value. Pause this async function until the promise settles, while other work can continue. Call getBriefing with the values inside the parentheses.
Line 105 if (requestedMission === mission)
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 105 log.textContent = message;
Replace the element’s displayed text. The browser treats the value as text.
Line 106 catch (error) {
Run this block if the try block throws an error.
Line 107 if (requestedMission === mission)
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Lines 107–109
Line 107 log.textContent = "Radio unavailable: " + error.message;
Plus adds numbers or joins text, depending on its values. Replace the element’s displayed text. The browser treats the value as text.
Line 108 finally {
Run this last block whether the earlier code succeeded or threw an error.
Line 109 button.disabled = false;
Store the result in the name or property to the left.

Mission challenge

Simulate a failed radio by changing the promise callback to accept a reject function and calling reject(new Error('Static')) inside the timer. Check that the briefing button reenables.

Change one piece at a time. Run the checkpoint again and compare what you expected with what actually happened.