Understanding Callbacks vs. Promises in JavaScript
Zeeshan Tanveer
Senior Software Engineer @ AlignPX | Laravel | PHP | Python | React | Node.js | AI & OpenAI | E-commerce & Shipping Solutions Specialist
Introduction
Asynchronous programming is fundamental in JavaScript to perform time-consuming tasks without blocking the main thread. Callbacks and Promises are two commonly used techniques for handling asynchronous operations. In this comprehensive guide, we will explain Callbacks and Promises in easy-to-understand terms, providing practical examples to illustrate their usage for beginners.
1. Callbacks: Introduction and Usage
1.1 What are Callbacks?
Callbacks are functions passed as arguments to another function and are executed after the completion of the original function. They are primarily used to handle asynchronous tasks in JavaScript, such as reading files, making API calls, or handling events.
1.2 Callback Example: Simple Timer
// Function that takes a callback and executes it after a specified dela
function delayedCallback(callback, delay) {
? setTimeout(callback, delay);
}
// Usage: Define the callback function
function greet() {
? console.log("Hello, this is a callback function!");
}
// Call the delayedCallback function with the greet callback after 2 seconds
delayedCallback(greet, 2000);
2. Promises: Introduction and Usage
2.1 What are Promises?
Promises are a cleaner and more structured way of handling asynchronous operations in JavaScript. They represent a value that might be available now or in the future, resolving to either success (fulfilled) or failure (rejected). Promises provide a chainable syntax, making error handling and code readability more straightforward.
2.2 Promise Example: Fetching Data from an API
// Function that returns a Promise for fetching data from an AP
function fetchDataFromAPI() {
? return new Promise((resolve, reject) => {
? ? fetch("https://api.publicapis.org/entries")
? ? ? .then((response) => response.json())
? ? ? .then((data) => resolve(data))
? ? ? .catch((error) => reject(error));
? });
}
// Usage
fetchDataFromAPI()
? .then((data) => console.log("Data fetched:", data))
? .catch((error) => console.error("Error fetching data:", error));
3. Key Differences: Callbacks vs. Promises
3.1 Error Handling
领英推荐
3.2 Chaining Multiple Asynchronous Operations
4. Introducing Async/Await with Promises
4.1 What is Async/Await?
Async/Await is a modern syntax built on top of Promises that allows developers to write asynchronous code that looks and feels like synchronous code. It simplifies the syntax and error handling further, enhancing code readability.
4.2 Async/Await Example: Fetching Data from Multiple APIs
// Function that uses async/await to fetch data from multiple API
async function fetchMultipleData() {
? try {
? ? const response1 = await fetch("https://catfact.ninja/fact");
? ? const data1 = await response1.json();
? ? const response2 = await fetch("https://www.boredapi.com/api/activity");
? ? const data2 = await response2.json();
? ? return [data1, data2];
? } catch (error) {
? ? throw new Error("Error fetching data:", error);
? }
}
// Usage
fetchMultipleData()
? .then((results) => console.log("Data fetched:", results))
? .catch((error) => console.error(error));
5. Choosing the Right Approach: Callbacks, Promises, or Async/Await
5.1 Callbacks
5.2 Promises
5.3 Async/Await
Conclusion
In this article, I have explored the concepts of Callbacks, Promises, and Async/Await in JavaScript. Understanding these concepts is crucial for effectively handling asynchronous operations in your applications. While Callbacks are widely used, Promises and Async/Await provide more organized and readable code, making them the preferred choices for modern JavaScript development. As you gain more experience, you will find that mastering asynchronous programming will significantly improve the efficiency and responsiveness of your JavaScript applications.