Asynchronous JavaScript
50 minJavaScript is single-threaded, meaning it can only do one thing at a time. Asynchronous programming allows it to perform long-running tasks (like fetching data) without freezing the interface.
The evolution of async JS went from **Callbacks** (prone to 'Callback Hell'), to **Promises** (chainable, cleaner error handling), to **Async/Await** (syntactic sugar that makes async code look synchronous).
A **Promise** represents a value that may not be available yet. It has three states: Pending, Fulfilled (Resolved), or Rejected. You consume it with `.then()` and `.catch()`.
**Async/Await** is the modern standard. An `async` function always returns a promise, and `await` pauses the execution of the function until the promise resolves, making code much easier to read and debug.
Key Concepts
- Synchronous vs. Asynchronous execution.
- The Callback Queue and Event Loop.
- Promises (Resolve, Reject, Then, Catch).
- Async/Await syntax.
- Error handling with Try/Catch in async functions.
Learning Objectives
Master
- Converting callbacks to promises
- Chaining multiple promises
- Using async/await for cleaner code
- Handling errors in async flows
Develop
- Reasoning about time and order in code
- Managing concurrent operations
- Debugging async race conditions
Tips
- Always use `try...catch` inside `async` functions to handle errors.
- Use `Promise.all()` to run independent async tasks in parallel (faster).
- Don't `await` inside a `forEach` loop (it won't wait); use `for...of` or `Promise.all(map)`.
- Return values from `.then()` to pass them to the next link in the chain.
Common Pitfalls
- Forgetting to `await` a promise, leading to race conditions.
- Nesting `.then()` calls deeply instead of chaining them (recreating callback hell).
- Swallowing errors (empty `.catch()`), making debugging impossible.
- Blocking the main thread with heavy computation (async only helps with I/O, not CPU tasks).
Summary
- Async JS prevents UI freezing.
- Promises manage future values.
- Async/Await is the modern, readable syntax.
- Error handling is crucial in async flows.
Exercise
Use the `fetch` API to get data from a public API and log the result. (This is a simulation).
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
Exercise Tips
- Add error handling with .catch() to handle network failures.
- Check response.ok before parsing JSON to handle HTTP errors.
- Try rewriting this using async/await syntax for comparison.
- Add loading states to show when the request is in progress.