FRONTENDO
Emberhold Forge
0
0
APIs & Async · The Fetch API
New technique

Meet fetch

fetch is how you send a runner: one call, and a request goes off to any server on the network.

fetch(url) is the built-in way to make HTTP requests: in every browser and in Node.js. It replaced the old XMLHttpRequest, and it speaks promises, so it fits right in with async/await.

Getting data takes two waits. First fetch resolves with a Response as soon as the status and headers arrive. The body may still be streaming in, so reading it is a second promise: res.json() reads the body and parses it as JSON.

async function loadSwords() {
  const res = await fetch("https://api.example.com/swords");
  const swords = await res.json();
  console.log(swords);
}
  • fetch returns a promise of a Response, not the data itself.
  • Forget the second await and swords is a promise, not an array.
  • Without options, fetch makes a GET request.