Simply Explained
Javascript fetch(): Simply Explained
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 withok
status set tofalse
insteadfetch()
will not receivecross-site cookies
fetch()
will not send cookies. Unless specially set in theinit
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 filerainbow.jpg
- Get the
response
containing the file with all themeta-data
of the request. This is also a promise - Chain the
promise
using another.then
to get theblob
image - Update the DOM using
.getElementById
URL.createObjectURL
is used to convert the format of theblob
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 thefetch
request from an external linkawait
for thejson
content of theresponse
to be extractedconsole.log
thestring
format of thejson
Another example with similar concept:
- Here
blogs[postId].file
returns the path to the file which I want tofetch
Resources
- The Coding Train: https://www.youtube.com/watch?v=tc8DU14qX6I&t=66s
- MDN web docs: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
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