Home » 3 Basic Ideas to Absolutely Perceive how the Fetch API Works | by Jay Cruz | Nov, 2023

3 Basic Ideas to Absolutely Perceive how the Fetch API Works | by Jay Cruz | Nov, 2023

by Icecream
0 comment

Cyberpunk-inspired scene with a cyborg Pitbull dog playing fetch.
Generated with DALL-E 3

Understanding the Fetch API could be difficult, notably for these new to JavaScript’s distinctive method to dealing with asynchronous operations. Among the various options of recent JavaScript, the Fetch API stands out for its skill to deal with community requests elegantly. However, the syntax of chaining .then() strategies can appear uncommon at first look. To absolutely grasp how the Fetch API works, it is important to grasp three core ideas:

In programming, synchronous code is executed in sequence. Each assertion waits for the earlier one to complete earlier than executing. JavaScript, being single-threaded, runs code in a linear trend. However, sure operations, like community requests, file system duties, or timers, may block this thread, making the consumer expertise unresponsive.

Here’s a easy instance of synchronous code:

perform doTaskOne() {
console.log('Task 1 accomplished');
}

perform doTaskTwo() {
console.log('Task 2 accomplished');
}

doTaskOne();
doTaskTwo();
// Output:
// Task 1 accomplished
// Task 2 accomplished

Asynchronous code, alternatively, permits this system to be non-blocking. JavaScript traditionally used callback features to deal with these operations, permitting the principle thread to proceed operating whereas ready for the asynchronous process to finish.

Here’s an instance of asynchronous code utilizing setTimeout, which is a Web API:

console.log('Start');

setTimeout(() => {
console.log('Task accomplished after 2 seconds');
}, 2000);

console.log('End');
// Output:
// Start
// End
// Task accomplished after 2 seconds (seems after a 2-second delay)

Callback features are the cornerstone of JavaScript’s asynchronous conduct. A callback is a perform handed into one other perform as an argument, which is then invoked contained in the outer perform to finish some form of motion.

Here’s an instance of utilizing a callback perform for an asynchronous operation:

You may also like

Leave a Comment