Skip to content

JavaScript Promises πŸš€ΒΆ

Prerequisites: JavaScript Functions

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ΒΆ

  1. Pending: Initial state, neither fulfilled nor rejected.
  2. Fulfilled (Resolved): The operation completed successfully.
  3. 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.");
    }
}
// πŸš€ Action: Using .then() and .catch()

pizzaPromise()
    .then(pizza => console.log("Eating: " + pizza))
    .catch(err => console.log("Oh no: " + err))
    .finally(() => console.log("Done."));

πŸ“Š 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


← Back: Callbacks | Next: Web Storage β†’