VCF

Unit 6 · JavaScript in the page

Why fetch gives you a Promise, not the data

fetch and functions built on it return a Promise, an IOU for the data, straight away. Put await in front to pause that function until the IOU pays out, however long the server takes.

The mix-up

What people often think

“fetchMenu() hands back the dishes straight away.”

What the tutor says

It hands back a promise, an IOU for the dishes. Write await fetchMenu() to wait for the IOU to pay out.

How it works

A fixed delay is a guess. A server can answer in ten milliseconds or ten seconds, and a slow one will beat your timer. await waits exactly as long as it takes.

await pauses only the function it is in. The rest of the page carries on, which is why code after the call to loadMenu() runs long before the response arrives. Show the data after the await, inside the async function.

Side by side

The mix-upJavaScript
const dishes = fetchMenu();   // a Promise
list.textContent = dishes;    // "[object Promise]"
Used before it arrives.
What worksJavaScript
async function loadMenu() {
  const dishes = await fetchMenu();
  list.textContent = dishes.join(", ");
}
Waits, then shows.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “Waiting a fixed time is the same as awaiting.”

    A server can take ten milliseconds or ten seconds. await waits exactly as long as it takes.

  • “A short delay will give the data time to arrive.”

    The delay is a guess, and a slow server will beat it. Show the dishes after the await, inside the async function.

  • “Code always runs top to bottom, so the dishes show before the next line.”

    await pauses only loadMenu. The rest of the page carries on, and loadMenu resumes when the answer arrives.

  • “Nothing else can run while a request is out.”

    The browser does other work during the wait. Code after loadMenu() runs long before the response comes back.

Practise it with a tutor watching

Async and fetch

Ask a server for data, wait for it with await, and show it when it arrives.

20 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.