1. The Callback (The Old Way)
A function passed into another function as an argument, to be executed later.
The Problem: If you have many nested callbacks, you get "Callback Hell" (code that looks like a sideways pyramid and is impossible to read).
2. The Promise (The Modern Way)
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. Think of it like ordering pizza: you get a receipt (the Promise) now, and the pizza (the Result) later.
Pending: Still working on it.
Resolved: Success! Here is your data.
Rejected: Error! Something went wrong.
The Code Example
// 1. A Basic Callback
function fetchData(callback) {
console.log("Fetching data...");
setTimeout(() => {
callback("Data received!"); // Runs after 2 seconds
}, 2000);
}
fetchData((message) => {
console.log(message);
});
// 2. Creating a Promise
const myRequest = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Mission Successful! 🚀");
} else {
reject("Mission Failed... ❌");
}
});
// 3. Consuming a Promise
myRequest
.then((result) => {
console.log(result); // Runs if resolved
})
.catch((error) => {
console.log(error); // Runs if rejected
})
.finally(() => {
console.log("Operation ended."); // Always runs
});