Now, let’s see how it happens…
fetch is a function and as this is asynchronous in nature we can do multiple operations at the same time that is time-independent so it will run in the background and let you know when it finishes so we get JSON data easily. also, we can Insert, Update, Read and Delete data on the server.
Syntax: Simply write fetch method using round brackets.
suppose I want to read the data of a file from the server, then I will give the path of that file inside the fetch method (the path can be of any server-side language). so basically it returns us the promise.
PROMISE: Used to handle asynchronous operations. It is an object that determines what happens after the event has happened
Whenever a promise is returned, It is either successful or it fails.
- CASE (I): IN first, we use then function with success. This also returns the promise.
fetch(URL) .then(); --------->promise
whatever data we get from fetch we will send it under then function that is the response. Here, response is a variable you can
give any name of variable. We do not print the variable, we return it. Now this data is in the form of JSON
- CASE(II): In the second case, We take the scenario of fail. If our server does not respond, We will get an error. In case of error, We use
So let’s see our code:
<script> fetch("https://jsonplaceholder.typicode.com/users") .then((response)=>response.JSON()) .then((data)=>console.log(data)) .catch((error)=>console.log("error")); </script>
Now here I bring fake data of JSON for that we can copy the URL of any data from JSON_PLACE_HOLDER site (you can use other sites also but I recommend this).
note: fetch method works on live server.
I hope, this article will be going to help you and write a comment if you are facing any difficulty.