Fetch API
Understand How to Use Fetch API in JavaScript: A Simple Guide for Beginners
The Fetch API is a modern way to make network requests and handle responses in JavaScript. It allows you to request resources from a server and handle responses. It is commonly used to fetch data from APIs or submit data to a server
Basic syntax :
fetch(url, options)
.then(response => response.json()) // Handling the response
.then(data => console.log(data)) // Log the data
.catch(error => console.error('Error:', error)); // Handling the errore
url
→ resource you are requesting (endpoint to request)options
→ An object specifying the request method, headers, body, etc..
Understanding how the Fetch API works :
Example code to understand
//My custom promise
const myPromise = new Promise((resolve, reject) => {
let success = true;
setTimeout(function() {
if (success) {
resolve("Task completed successfully!");
} else {
reject("Task failed !!!");
}
}, 1000)
});
myPromise
.then(result => {
console.log(result); // Runs if resolved
})
.catch(error => {
console.error(error); // Runs if rejected
})
// fetch my github data using Fetch API
fetch('https://api.github.com/users/AkLuffy07')
.then(response => {
return response.json();
})
.then(data => {
console.log("GitHub Data :: ", data);
})
.catch(err => console.log(err))
.finally(() => console.log("Fetch method is completed.."))
In the above code, created a myPromise
and a fetch
method.
As we know the promises handles the task that takes time, So If you run the above code, you will get the fetch API response first, and after that you will get the myPromise response
Let's take a deep dive into the functionality and how it internally works..
Figure 1 :
In JavaScript, the execution process involves the JS engine, memory, and call stack. The global execution context is placed in the call stack, and on top of that, function execution contexts are added as functions are invoked.
Execution follows a top-to-bottom approach. When a new function is called, it is pushed onto the top of the stack and executed first.
Some functions, like
setTimeout
, operate differently. WhensetTimeout
is used, its callback is registered and placed inside the task queue.The event loop continuously monitors whether the task queue contains pending tasks and whether the call stack is empty.
Once the call stack is clear, the callback is moved to the top of the stack and executed by the JS engine.
In the case of the Fetch API
, the callback is registered in a separate queue called the microtask queue (also known as the priority queue). The microtask queue is always prioritized over the task queue, meaning its functions are executed first in the call stack before any tasks from the task queue are processed.
Key points about Fetch API:
Promise-based: Easy to handle asynchronous operations.
Thenable: Supports
.then()
chaining.Flexible: Can handle various request types (
GET
,POST
,PUT
,DELETE
)Built-in: No need to install external libraries.
Conclusion
The Fetch API is a powerful tool for making network requests.
.then()
,.catch()
, and.finally()
handle responses and errors effectively.Understanding the Fetch API is essential for working with web applications that interact with servers