Asynchronous I/O Lesson

### Concept Window Asynchronous I/O lets a program start a task that may take time without freezing everything else. Loading a file, calling an API, or waiting for a database response should not stop the whole page from working. Promises represent values that will be available later. The async and await keywords make promise-based code easier to read because it looks closer to normal step-by-step code.

Code Runner Challenge

Asynchronous I/O Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Asynchronous I/O Lesson

async function loadMessage() {
  console.log("Request started");

  const response = await fetch("/message.txt");
  const text = await response.text();

  console.log("Message loaded: " + text);
}

loadMessage();
console.log("This can run while the request is waiting");
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

The request starts inside the async function, but the rest of the program can continue. When the response arrives, await gives the function the loaded text.