JavaScript is single-threaded, meaning it executes code sequentially. Asynchronous JavaScript allows tasks to run independently of the main thread, enabling non-blocking operations such as fetching data, timers, and event handling.

💡 Why Asynchronous?
Asynchronous code prevents the UI from freezing by allowing long-running tasks (like network requests) to run in the background.
Core Concepts
- Callbacks: Functions passed as arguments to be executed later.
- Promises: Objects representing eventual completion or failure of async operations.
- Async/Await: Syntax sugar to write asynchronous code that looks synchronous.
1. Callbacks
Callbacks are the oldest way to handle async code. A function is passed as an argument and called when the async task finishes.
📌 Deep Dive: Callback Example
function fetchData(callback) {
setTimeout(() => {
callback('Data loaded');
}, 1000);
}
fetchData(message => {
console.log(message);
});
⚠️ Callback Hell
Multiple nested callbacks can lead to hard-to-read and maintain code, known as "callback hell."
2. Promises
Promises represent a value that may be available now, later, or never. They have three states: pending, fulfilled, or rejected.
📌 Deep Dive: Promise Example
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data loaded via Promise');
}, 1000);
});
fetchData.then(message => console.log(message));
3. Async/Await
Async/await is syntactic sugar over promises, allowing you to write asynchronous code that looks synchronous, improving readability.
📌 Deep Dive: Async/Await Example
function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Data loaded with async/await');
}, 1000);
});
}
async function getData() {
const message = await fetchData();
console.log(message);
}
getData();
| Feature | Callbacks | Promises | Async/Await |
|---|---|---|---|
| Syntax | Nested functions | Then/catch chains | Looks synchronous |
| Error Handling | Manual and complex | Using .catch() | Try/catch blocks |
| Readability | Poor with nesting | Improved | Best, clean code |
| Control Flow | Difficult | Better with chaining | Very intuitive |
💡 Event Loop Overview
The event loop manages asynchronous operations by handling the call stack and task queue, ensuring async callbacks execute after the current execution completes.
⚠️ Avoid Blocking Code
Heavy synchronous tasks block the event loop and freeze interfaces. Use asynchronous patterns to keep apps responsive.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which asynchronous pattern helps avoid "callback hell" by using .then() and .catch() methods?
Question 2 of 2
What keyword is used to declare a function that allows the use of "await" inside it?
Loading results...