JavaScript Promises ๐¶
Mentor's Note: In life, you don't wait for the laundry to finish before starting to cook dinner. You do both! Asynchronous JavaScript allows your code to "Wait in the background" while other things keep running. ๐ก
๐ The Scenario: The Pizza Shop ๐¶
Imagine you order a pizza at a local restaurant.
- The Order (The Promise): You pay your money and the clerk gives you a Buzzer (The Promise Object). ๐ฆ
- The Process (The Wait): The buzzer is currently "Pending." You can go back to your table and talk to friends (Asynchronous execution). ๐ฆ
- The Result:
- Success (Resolved): The buzzer rings! You get your pizza. ๐
- Failure (Rejected): The clerk tells you they ran out of dough. You get an apology. โ
- The Result: You only stop what you're doing once the buzzer rings! โ
๐ Concept Explanation¶
1. What is a Promise?¶
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
2. The 3 States¶
- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled (Resolved): The operation completed successfully.
- Rejected: The operation failed.
๐จ Visual Logic: The Timeline¶
graph LR
A[Order Pizza ๐] --> B{Wait... โณ}
B -- "Success โ
" --> C[Eat! (.then)]
B -- "Error โ" --> D[Refund! (.catch)]
C --> E[Finally done.]
D --> E
๐ป Implementation: The Async Lab¶
// ๐ Scenario: Ordering Pizza
// ๐ Action: Using await to pause logic nicely
async function getDinner() {
console.log("Ordering pizza... ๐");
try {
// Wait for the oven (The Promise)
const pizza = await pizzaPromise();
console.log("Eating " + pizza + "! ๐");
} catch (error) {
console.log("Error: " + error); // ๐๏ธ If shop is closed
} finally {
console.log("Dinner time over.");
}
}
๐ Sample Dry Run¶
| Time | Code Line | Action | Status |
|---|---|---|---|
| 0ms | fetchData() |
Start Request ๐ค | Pending โณ |
| 10ms | console.log("Hi") |
Runs immediately! | Running |
| 500ms | await finishes |
Request returns ๐ฅ | Resolved โ |
๐ Technical Analysis¶
- Microtasks: Promises have their own high-priority queue in the JavaScript Event Loop. โก
- Why use them?: To avoid Callback Hell (Pyramid of Doom), where your code keeps shifting right until it's unreadable.
๐ฏ Practice Lab ๐งช¶
Task: The Data Fetcher
Task: Write an async function that uses the fetch() API to get data from https://jsonplaceholder.typicode.com/todos/1. Print the title of the todo.
Hint: const response = await fetch(url); const data = await response.json();. ๐ก
๐ก Interview Tip ๐¶
"Interviewers love to ask: 'Does await block the main thread?' Answer: NO. It only pauses the execution of the async function itself, allowing the rest of the browser to stay responsive."
๐ก Pro Tip: "Asynchronous programming is about efficiency. Don't wait for one thing to finish when you can do ten other things in the meantime!" - Anonymous