Async JavaScript
JavaScript is single-threaded but non-blocking. It achieves this through the Event Loop. Understanding async is essential for handling I/O, API calls, timers, and user events.1. The Event Loop
JavaScript has one main thread. Long operations would block everything. The solution? Asynchronous callbacks.How It Works
- Call Stack: Synchronous code executes here (LIFO).
- Web APIs: Browser handles async operations (setTimeout, fetch, DOM events).
- Task Queue: Callbacks wait here when async operations complete.
- Event Loop: Moves callbacks from queue to stack when stack is empty.
Microtasks vs Macrotasks
Microtasks (Promises, queueMicrotask) have higher priority than Macrotasks (setTimeout, setInterval).2. Callbacks
A callback is a function passed to another function to be executed later.Callback Hell
Nested callbacks become unreadable and hard to maintain.3. Promises
A Promise represents a value that may be available now, later, or never. It’s a cleaner alternative to callbacks.Promise States
| State | Description |
|---|---|
pending | Initial state, neither fulfilled nor rejected |
fulfilled | Operation completed successfully |
rejected | Operation failed |
Creating a Promise
Consuming a Promise
Chaining Promises
Each.then() returns a new Promise, enabling chaining.
Promise Static Methods
4. async/await (ES2017)
async/await is syntactic sugar over Promises. It makes async code look synchronous.
Basic Usage
Comparison
Error Handling
Parallel Execution
Sequential (Slow):Top-Level Await
In ES modules, you can useawait at the top level.
5. Common Async Patterns
Retry with Exponential Backoff
Debounce
Wait for a pause before executing (e.g., search input).Throttle
Limit execution to once per interval (e.g., scroll handler).Async Queue
Process items one at a time.6. Fetch API
The modern way to make HTTP requests.Summary
- Event Loop: Enables non-blocking I/O on a single thread.
- Callbacks: Simple but lead to callback hell.
- Promises: Chainable, cleaner error handling with
.catch(). - async/await: Synchronous-looking async code. Use
try/catchfor errors. - Parallel Execution: Use
Promise.all()to run independent operations concurrently.