JavaScript Fetch API
Unlocking the Potential of API Calls with the Fetch API in JavaScript
Introduction
The fetch API in JavaScript is used to request data from a server. Think of the fetch method as the two-pronged facade function,
Fetch API was introduced in ES6, it was introduced as the successor of XMLHttpRequest which was used for making asynchronous calls in web applications. As we can see in the above diagram, the fetch method does two things,
Set up a network request in the web browser
Returns a special object called Promise. You can think of Promise as a placeholder object for a task yet to be finished.
Let's see an example,
// function to display data
function display(data){
console.log(data);
}
// requesting data from twitter
const futureData = fetch('https://twitter.com/something');
futureData.then(display);
console.log('Me, first');
/*
Output:
Me, first
Hello, World
*/
Let's understand the above code,
Line 1: We are declaring a function called display
in the global memory.
Line 2: We declared a constant named futureData
and assigned the value returned by our fetch method which is a promise.
Line 3: We are using then
method on our constant to handle the asynchronous request, the data is passed to display function as an argument when the response is received.
Line 4: We are logging "Me, First" in the console.
Promises
In simple words, a promise is a special object which acts like a placeholder for an asynchronous task that is yet to be completed. There are states associated with promise,
pending: initial state, neither fulfilled nor rejected
fulfilled: the task was completed successfully
rejected: the task was failed
The onFulfilled[]
is a hidden property in a promise. Any functionality here gets automatically triggered when the value property is set. So, in the above program if somehow we put display
function in this array, it gets automatically gets run.
Since it is an array,
We can use
push
method to put our function in theonFulFilled
property.But since it is a hidden property, so we cannot use
push
method.
This is why JavaScript provides us with then
method, which lets us push functions in that hidden property.
There is another hidden property called onRejected
property, and JavaScript provides us with catch
method which lets us push functionality into this property and it also gets automatically triggered when the promise gets rejected.
Let's see an example,
function makeRequest(){
return new Promise((resolve, reject) => {
// simulating delayed response
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber < 0.5) {
resolve({ message: "Promise resolved successfully." });
} else {
reject({ error: "Promise rejected due to random error." });
}
}, 2000);
});
}
// calling function
makeRequest()
.then((data) => {
console.log(data.message);
})
.catch((error) => {
console.error(error.error);
});
In this example, the makeRequest
function returns a new Promise. Inside the Promise, a setTimeout
function is used to simulate a delayed response. After 2 seconds, a random number is generated,
If the number is less than 0.5, the Promise is resolved with a success message
If the number is greater than 0.5, the Promise is rejected with an error message
When the promise is resolved, the then
method is called, and the success message is logged to the console. If the promise is rejected, the catch
method is called, and the error message is logged to the console.
Microtask Queue
Promises are always handled asynchronously, as all promise actions pass through the microtask queue. The Microtask queue is handled by the event loop before it moves on to the next task in the callback queue.
In the above code, when the promise gets resolved the display
function is queued into the microtask queue,
Rules for execution of our asynchronously delayed code
Hold promise-deferred functions in a microtask queue and callback function in a task queue or callback queue when the web browser finishes.
Add the function to the call stack when the call stack is empty and all synchronous code gets executed.
Prioritize functions in the microtask queue over the callback queue.
Conclusion
In this blog, we discussed the fetch method in JavaScript. We also talked about promises and how they use microtask queues. We also saw some rules for executing asynchronously delayed code.
If you're having any doubts please mention them in the comments below! ๐