HomeAbout

Fetch

What is fetch

fetch() is used to accesses resources across the network

fetch accepts two parameters:

  • resource accepts URL string or Request object.
  • options accepts object with attributes like method, headers, body.
const response = await fetch(resource[, options]);

Return Value

fetch() starts a request and returns a Promise.

  • If the request fails due to network problems, the Promise is rejected
  • when the request is complete, the Promise is resolved with the Response object

Handling failed requests

fetch(request) .then((response) => { if (response.status === 200) { return response.json(); } else { throw new Error("response status is not 200, request failed"); } }) .then((response) => { console.debug(response); // … }) .catch((error) => { console.error(error); });
AboutContact