🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript fetch

fetch is a built-in function that asks a source for data. It returns a promise of a response.

Fetching JSON

fetch asks the data URL for its JSON. await pauses the function until the response arrives.

(async () => {
  const response = await fetch("data:application/json,%7B%22name%22%3A%22Ana%22%7D");
  const data = await response.json();
  console.log(data.name);
})();

Reading plain text

A data URL can hold plain text too. The response status is 200, which means success.

(async () => {
  const response = await fetch("data:text/plain,Hello");
  console.log(response.status);
  console.log(await response.text());
})();

fetch with .then

fetch works with .then as well as with await. Each .then step hands its result to the next step.

fetch("data:application/json,%7B%22city%22%3A%22Lisbon%22%7D")
  .then((response) => response.json())
  .then((data) => { console.log(data.city); });

Example

(async () => {
  const response = await fetch("data:application/json,%7B%22title%22%3A%22Fetch%20lesson%22%2C%22pages%22%3A12%7D");
  const data = await response.json();
  console.log(data.title);
  console.log(data.pages);
})();

Key points

  • Response: an object that holds the answer to a fetch, with its status and its body
  • fetch returns a promise, so the response arrives later.
  • .json(): a method that reads a response body as JSON
  • .text(): a method that reads a response body as plain text
  • A data: URL holds its data inside the URL itself, so no network is needed.
  • The response body can be read only once.

In this example, fetch asks the data URL for its JSON. The await pauses the function until the response arrives. The last two lines print the two fields from the parsed data.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does fetch return?