🚀 Alguni Start learning

Unit 10: Waiting & The Web

Code that finishes later.

Unit 10 of 10 in JavaScript for kids. Its 6 lessons are Callbacks, Promises, async & await, One Thing At A Time, The Page and Web Ready — below is everything each one explains, and a question or two from it to try.

Every sample on this page was run before it shipped, the same way the app runs it, and prints exactly what it says it prints.

This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.

📞 Callbacks

Handing over a job

A callback is a function you give to someone else so they can run it when they are ready. You already did this with map and filter.

JavaScript

function doTwice(action) {
  action();
  action();
}

doTwice(() => console.log("jump"));

It prints

jump
jump

The callback gets told things

Whoever calls your function decides what to hand it. forEach passes the item and its position.

JavaScript

["a", "b"].forEach((item, i) => {
  console.log(i, item);
});

It prints

0 a
1 b

Come back in one second

setTimeout takes a callback and a delay. It does not pause your program — the rest carries straight on, and the callback runs later. So this prints first, then second, and only a second afterwards does last appear.

(That "later" is why this one is not runnable in the lesson editor: our checker reads what your code printed the moment it finishes, so a line that arrives a second late arrives too late.)

JavaScript

console.log("first");

setTimeout(() => {
  console.log("last");
}, 1000);

console.log("second");

Try it yourself

What is a callback?

  • A phone number
  • A function handed to other code, to be run later by that code
  • A loop that repeats
  • A kind of variable

In what order do those three lines appear?

  • first, last, second
  • first, second, last
  • last, first, second
  • All at the same time

Answer them in the app

🤞 Promises

A receipt for an answer

A promise is what you get when the answer is not ready yet — like a ticket at a chip shop. Later it either resolves with the answer, or rejects with a problem.

JavaScript

const chips = new Promise((resolve) => {
  setTimeout(() => resolve("your chips"), 1000);
});

chips.then((food) => console.log(food));

then, then, catch

Each .then waits for the one before it, so a chain reads top to bottom even though it happens over time. One .catch at the end handles a problem anywhere in the chain.

JavaScript

loadScores()
  .then((scores) => scores.filter((s) => s > 5))
  .then((big) => console.log(big.length))
  .catch((err) => console.log("Could not load:", err.message));

Try it yourself

What is a promise?

  • A value that is definitely there
  • A stand-in for an answer that has not arrived yet
  • A kind of loop
  • A function that never fails

What does .catch at the end of a chain do?

  • Nothing
  • Handles a problem from any step of the chain
  • Only handles the last step
  • Repeats the chain

Answer them in the app

⏳ async & await

Waiting, written the easy way

await waits for a promise and hands you the answer, so waiting code looks like normal code. It is only allowed inside a function marked async.

JavaScript

async function showScores() {
  const scores = await loadScores();
  console.log(scores.length);
}

showScores();

The same try/catch you already know

With await, a rejected promise behaves like a thrown error — so you catch it with the try/catch from the last unit instead of .catch.

JavaScript

async function showScores() {
  try {
    const scores = await loadScores();
    console.log(scores.length);
  } catch (err) {
    console.log("Could not load it");
  }
}

Try it yourself

What does await do?

  • Freezes the whole page until the answer arrives
  • Pauses just that function until the promise is done, letting everything else carry on
  • Makes the code faster
  • Cancels the promise

What does an async function always hand back?

  • A number
  • A promise
  • undefined
  • Nothing at all

Answer them in the app

🔁 One Thing At A Time

The queue

JavaScript only ever runs one piece of code at a time. Anything waiting — a timer, a click, an answer from the internet — joins a queue, and JavaScript picks the next job up only once it has finished the current one. That loop of "finish this, take the next" is the event loop.

Try it yourself

What does setTimeout(fn, 0) really mean?

  • Run fn right now
  • Run fn as soon as the code that is running now has finished
  • Never run fn
  • Run fn before everything else

In what order do these print? console.log("A"); setTimeout(() => console.log("B"), 0); console.log("C");

  • A B C
  • A C B
  • B A C
  • C A B

Answer them in the app

🌐 The Page

What JavaScript was made for

In a browser, the page is an object called document and JavaScript can change it. querySelector finds a piece of the page, and textContent reads or replaces the words inside it.

(These samples need a real web page, so they will not run in the lesson editor.)

JavaScript

const title = document.querySelector("h1");
title.textContent = "Hello!";

Waiting for a click

addEventListener says "when this happens, run that". It takes the name of the event and a callback — the same idea as setTimeout, but triggered by a person instead of a clock.

JavaScript

const button = document.querySelector("button");

button.addEventListener("click", () => {
  console.log("clicked!");
});

Try it yourself

What is the DOM?

  • A kind of loop
  • The page, as objects your code can read and change
  • A website
  • A file on your computer

How many times can one button have a click listener added?

  • Once only
  • As many as you like — every one of them runs
  • Twice
  • None, buttons cannot be listened to

Answer them in the app

🏆 Web Ready

Try it yourself

In what order do these print? console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4);

  • 1 2 3 4
  • 1 4 3 2
  • 1 4 2 3
  • 1 3 4 2

Which pair does the same job?

  • .then and for...of
  • .then and await
  • .catch and finally
  • async and setTimeout

Answer them in the app