Detailed explanations & code examples are in the JavaScript (.js) file
Click the { } button at the bottom right to view it
Master Callbacks, Promises, Async/Await, and Fetch API
Understanding how JavaScript handles blocking and non-blocking code
setTimeout(callback, milliseconds)callback - Function to execute after delaymilliseconds - Delay time (1000ms = 1 second)Watch the execution order - Tasks 2, 3, 4 run immediately while Task 1 waits 3 seconds!
The problem with deeply nested callbacks
// This is Callback Hell - hard to read! task1(() => { task2(() => { task3(() => { task4(() => { console.log("Done"); }) }) }) })
| Problem | Description |
|---|---|
| Hard to Read | Pyramid shape makes code confusing |
| Difficult to Debug | Errors are hard to track down |
| Messy Error Handling | Need separate error handlers for each callback |
| Hard to Maintain | Adding/removing steps is complicated |
4 nested tasks that execute sequentially - demonstrates the "pyramid" structure
Handle asynchronous operations with cleaner syntax
| State | Description |
|---|---|
| PENDING | Initial state, operation in progress |
| RESOLVED (fulfilled) | Operation completed successfully |
| REJECTED | Operation failed |
new Promise((resolve, reject) => { if(success){ resolve("Success!"); // Resolved } else{ reject("Failed!"); // Rejected } });
.then() waits for Promise before moving foward() => step2() - implicit return (returns promise without having to write return)() => { step2(); } - returns undefined (if in {} return is required)() => { return step2(); } - explicit return (returns promise with having to write return).catch() catches ANY rejection in the chain
Write asynchronous code that looks synchronous
async - Makes function return a Promiseawait - Pauses function until Promise resolvestry/catch for error handlingasync function fetchData(){ try { const result = await someAsyncOperation(); console.log(result); } catch(error) { console.error(error); } }
| Feature | Promises (.then) | Async/Await |
|---|---|---|
| Syntax | Chaining .then() | Sequential await |
| Readability | Can get messy | ✅ Clean, linear |
| Error Handling | .catch() at end | ✅ try/catch blocks |
| Modern? | Still used | ✅ Preferred |
Make HTTP requests to APIs/resources and fetch data
fetch(url, {options})| Method/Property | Description |
|---|---|
response.ok |
Boolean - true if status 200-299 |
response.json() |
Parses JSON - JavaScript object (returns Promise) |
response.text() |
Parses response as plain text |
response.blob() |
Parses as binary data (images, files) |
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
async function fetchData(){ const res = await fetch(url); const data = await res.json(); }
Fetch real Pokémon data from API! Try both methods:
Loading...