JavaScript handles asynchronous operations using callbacks, promises, and async/await. Here's how:
✅ 1. Callbacks
A function passed into another function to be executed later (e.g., after an API call or timer).
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched");
}, 1000);
}
fetchData((result) => {
console.log(result); // ➝ "Data fetched"
});
✅ 2. Promises
An object representing the eventual completion or failure of an asynchronous task.
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
};
fetchData()
.then((data) => console.log(data))
.catch((err) => console.error(err));
✅ 3. async/await
Syntactic sugar over promises to write cleaner, synchronous-looking async code.
const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
};
async function handleData() {
const result = await fetchData();
console.log(result); // ➝ "Data fetched"
}
handleData();
🔁 Summary:
- Use callbacks for simple cases (but can lead to "callback hell").
- Use promises for better chaining and error handling.
- Use async/await for cleaner and more readable async code.