Quick Reference
Concept |
Description |
Callbacks |
Legacy async approach, leading to "Callback Hell." |
Promises |
.then() , .catch() , .finally() for structured async handling. |
async/await |
Syntax sugar for Promises, improving readability. |
Event Loop |
Manages macrotasks (task queue) & microtasks (Promise queue). |
Callbacks (Legacy)
- A function passed as an argument to another function to handle async operations.
function fetchData(callback) {
setTimeout(() => callback("Data loaded"), 1000);
}
fetchData(console.log); // "Data loaded"
Promises
- Represents a future value that may resolve (
fulfilled
) or reject (rejected
).
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success!"), 1000);
});
myPromise.then(result => console.log(result)); // "Success!"
Method |
Description |
.then(callback) |
Executes when resolved. |
.catch(callback) |
Executes on rejection. |
.finally(callback) |
Runs regardless of resolve/reject. |
Promise.all([...]) |
Resolves when all promises succeed, rejects if one fails. |
Promise.allSettled([...]) |
Resolves with results of all, never rejects. |
Promise.race([...]) |
Resolves/rejects as soon as the first promise settles. |
Promise.any([...]) |
Resolves with first successful, rejects if all fail. |
Promise.all([fetch(url1), fetch(url2)])
.then(responses => console.log("All completed:", responses))
.catch(err => console.error("One failed:", err));
Promise.race([fetch(url1), fetch(url2)])
.then(response => console.log("First completed:", response));
Promise.any([fetch(url1), fetch(url2)])
.then(console.log)
.catch(console.error);
- Chaining:
.then()
always returns a new Promise, enabling chain operations.
myPromise
.then(res => res + " modified")
.then(res => console.log(res)); // "Success! modified"
async/await
async
functions always return a Promise.
await
pauses execution until the Promise resolves.
async function fetchData() {
try {
const response = await fetch('<https://jsonplaceholder.typicode.com/todos/1>');
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
fetchData();
await
only works inside async
functions.
- Top-level
await
is supported in ES modules.
// Works in modules (not in regular scripts)
const data = await fetch(url).then(res => res.json());
console.log(data);
- Errors in
async
functions reject the Promise.