Callbacks — Understanding JavaScript API Requests and Responses in the Data Fetching lifecycle
Rodrigo Castilho
Posted on April 10, 2023
Before this article, I mentioned to you that I would start the articles series and I created an Introduction, and about the V8 JavaScript engine. If you lost what I did, check it:
In this article series, I’ll not explain the concept of Promises or async/await but don’t worry that I’ll explain in the next article.
In summary, A callback is a programming technique in which a function is passed as an argument to another function and is executed at a later time, usually after a task has been completed. This technique is commonly used in asynchronous programming and event-driven programming, and the purpose of a callback is to allow a function to call back or notify the caller when it has completed a task or some operation.
Callbacks are a powerful programming technique in JavaScript that allows for flexible and efficient asynchronous programming. They can be used to handle complex and long-running operations, handle user input or browser events, pass data between functions, and more.
Here’s a simple example of how callback works using a calculator passing a callback function as an argument.
In the example below, the calculator function receives parameters x and y as a number and callback as a function and returns the result of invoking the callback function with x and y as arguments.
function calculator(x, y, callback) {
return callback(x, y);
}
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
function multiply(x, y) {
return x * y;
}
function divide(x, y) {
return x / y;
}
console.log(calculator(10, 2, add)); // Output: 12
console.log(calculator(10, 2, subtract)); // Output: 8
console.log(calculator(10, 2, multiply)); // Output: 20
console.log(calculator(10, 2, divide)); // Output: 5
Where I can use callbacks?
Callbacks can be used in a variety of contexts in JavaScript. Here are some common examples:
Asynchronous programming: Callbacks are commonly used to handle asynchronous operations, such as fetching data from a server or reading a file from a disk. When an asynchronous operation completes, the callback is executed to handle the result.
In the example below, the fetch() function is called with a URL argument to send an HTTP request to the specified URL and retrieve data from it. In this case, we’re requesting the Chuck Norris Jokes API to get a random joke.
fetch("https://api.chucknorris.io/jokes/random")
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error(`Error: ${error}`))
.finally(() => console.log("Fetch complete!"));
Event-driven programming: Callbacks are often used to handle events in a web application, such as mouse clicks, keyboard input, or form submissions. When an event occurs, the callback is executed to handle the event.
In the example below, image a button tag in HTML and will add the click action.
const button = document.querySelector("button");
function handleClick(event) {
console.log("Button clicked!");
}
button.addEventListener("click", handleClick);
Callback-based APIs: Some JavaScript libraries and frameworks use callbacks as a way to provide a simple and flexible interface for developers to interact with their APIs. For example, the Node.js file system API uses callbacks to provide a simple and flexible way to read and write files on the server.
In the example below, define a function called sayHello that returns the string “Hello World!”. I used the setTimeout function to schedule the sayHello function to be called after a delay of 1000 milliseconds (i.e., 1 second).
function sayHello() {
console.log("Hello World!");
}
setTimeout(sayHello, 1000);
Modular programming: Callbacks can be used to pass functions between modules in a program, allowing for more flexible and modular code. For example, a module that generates random numbers could use a callback function to allow the caller to specify how the number should be used.
In the example below, define a function called sayMyName that takes a callback function as a parameter. Inside the sayMyName function, we define a variable called name and assign it the value “Rodrigo”. When the sayHello function is called, it logs the message “Hello World Rodrigo!” to the console.
function sayMyName(callback) {
const name = "Rodrigo";
callback(name);
}
function sayHello(name) {
console.log(`Hello World ${name}!`);
}
sayMyName(sayHello);
What does Callback Hell mean also known as Pyramid of Doom
Excessive use of callbacks can lead to complex and difficult-to-read code, so it’s important to use them judiciously and consider alternative techniques when appropriate.
To avoid these issues, it is important to use callbacks judiciously and consider alternative techniques when appropriate. Promises and async/await syntax are newer language features in JavaScript that can provide more powerful and flexible alternatives to callbacks.
So, If you want to know more about promises, and async/await, please wait for the next article that I’ll publish.
Thank you for reading, I hope this article can somehow have increased your knowledge base about it.
Posted on April 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.