LE VAN TUAN LONG
Welcome to my page where I write about multiple things such as programming, quant trading, machine learning and others...

Basic Guide to Fetch function in JavaScript

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.

1
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 https://developer.mozilla.org/en-US/docs/Web/API/Body)

1
2
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
1
2
3
4
5
fetch('rainbow.jpg').then(response => {
    return response.blob();
}).then(blob => {
    document.getElementById('rainbow').src = URL.createObjectURL(blob);
})

Another example

1
2
3
4
5
6
7
const myImage = document.querySelector('.my-image');
fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
    .then(res => res.blob())
    .then(res => {
        const objectURL = URL.createObjectURL(res);
        myImage.src = objectURL;
});

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
1
2
3
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
console.log(JSON.stringify(myJson));

Another example with similar concept:

  • Here blogs[postId].file returns the path to the file which I want to fetch
1
2
3
4
5
const getBlogContent = async (postId: string) => {
    const response = await fetch(blogs[postId].file);
    const text = await response.text();
    await setText(text);
};

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