Fetch
Fetch
fetch -->
- The fetch() API is a modern and powerful way to make asynchronous HTTP
requests to servers in JavaScript.
- It returns a Promise that resolves to the Response object representing the
response to the request.
2. Syntax
fetch(url, options)
.then(response => {
// Handle the response
})
.catch(error => {
// Handle any errors
});
- response.json(): Converts the response body into JSON. This also returns a
Promise.
4. Example Explained
fetchedData.then((data) => {
// First .then block to handle the response
let jsonData = data.json(); // Convert response to JSON
console.log(jsonData); // Logs the Promise of the parsed JSON
jsonData.then((finalData) => {
// Second .then block to handle the parsed JSON data
console.log(finalData); // Logs the final parsed data
finalData.map((e) => {
console.log(e.login); // Logs the 'login' property of each user
});
});
});
5. Chaining Promises
- The fetch() method returns a Promise. After calling fetch(), you can chain
multiple .then() methods to handle the response and data.
- Nested Promises: In the example, the first .then() handles the Response
object and parses it to JSON, while the second .then() handles the actual
data.
// ! taking all the data from api and print on the ui
fetchedData1.then((data)=>{
jsonData.then((finalData)=>{
finalData.map((ele)=>{
let li = document.createElement("li")
li.innerText = ele.login;
container.append(li)
})
}).catch((err)=>{
console.log(err)
})
}).catch((err)=>{
console.log(err)
})