Simply Explained

Javascript fetch(): Simply Explained

Le Van Tuan Long
Tech Front
Published in
2 min readMay 10, 2020

--

When I was learning Javascript, I was often confused about the purpose and implementation details of the fetch() function. With this article, I would hope to explain simply to the readers about the purpose of fetch() and a basic implementation of the function.

1. Why do we need the `fetch` function?

fetch() function is a global method by JavaScript which allows us to retrieve resources asynchronously across the network

2. How is `fetch` different from `ajax` call?

  • fetch() will not reject on HTTP error status (e.g. 404 & 500). It will resolve with ok status set to false instead
  • fetch() will not receive cross-site cookies
  • fetch() will not send cookies. Unless specially set in the init option

3. How does the `fetch` function work?

fetch takes in one or more arguments. For the most basic case, fetch just takes in one argument which is the path to the resource you want to fetch.

fetch('http://example.com/movies.json')

fetch function returns a promise which is a Response object. In order to extract the body of content from the Response object, you need to use Body mixin of the Fetch API (More information can be found here)

const response = await fetch(‘http://example.com/movies.json');
const myJson = await response.json();

4. Implementation code examples

4a. Using `.then` method

What we are trying to achieve here are:

  • fetch a local file rainbow.jpg
  • Get the response containing the file with all the meta-data of the request. This is also a promise
  • Chain the promise using another .then to get the blob image
  • Update the DOM using .getElementById
  • URL.createObjectURL is used to convert the format of the blob to something which is usable by the <img> tag

Another example

4b. Using `async/await` method

What we are trying to achieve here are:

  • await for the fetch request from an external link
  • await for the json content of the response to be extracted
  • console.log the string format of the json

Another example with similar concept:

  • Here blogs[postId].file returns the path to the file which I want to fetch

Resources

Disclaimer

  • All information mentioned on this blog post is based on my subjective and limited knowledge. Any feedback is welcomed
  • Full credits are given to the resources used

--

--

Le Van Tuan Long
Tech Front

Technology writer. A software engineer by trade. Follow me on Twitter and Linkedin @levanify