Promises and then in JavaScript - JavaScript

 

Ever asked someone for a favor, and they said, "I'll do it later"? That’s basically how JavaScript promises work! A Promise in JavaScript is like a pinky promise—it either gets fulfilled (yay!) or rejected (ouch!). And to handle what happens next, we use .then().

1. What is a Promise? 

A Promise is an object that represents a future value. It can be:

  • Pending  (Still waiting… like when you order pizza)
  • Fulfilled  (Your pizza arrives!)
  • Rejected  (The restaurant canceled your order!)

Example:

let pizzaPromise = new Promise((resolve, reject) => {
    let pizzaArrives = true;
    
    setTimeout(() => {
        if (pizzaArrives) {
            resolve("Pizza is here!");
        } else {
            reject("Sorry, no pizza today");
        }
    }, 2000);
});

2. Handling Promises with .then()

When a Promise is fulfilled, .then() allows us to handle the result.

Example:

pizzaPromise.then((message) => {
    console.log(message); // "Pizza is here!"
}).catch((error) => {
    console.log(error); // "Sorry, no pizza today"
});

Analogy: .then() is like getting a notification when your pizza arrives, while .catch() is when you get a refund because the pizza place ran out of ingredients.

3. Chaining Promises

Sometimes, you need to do multiple things in order. Promise chaining makes this easy.

Example:

pizzaPromise
    .then((message) => {
        console.log(message);
        return "Now eating the pizza! 🍽️";
    })
    .then((nextStep) => {
        console.log(nextStep);
    })
    .catch((error) => {
        console.log(error);
    });

Analogy: Like tracking your pizza order: Order placed → Pizza being prepared → Out for delivery → Delivered! 

4. Error Handling with .catch() 

Sometimes things go wrong. .catch() helps handle errors gracefully.

Example:

let badPromise = new Promise((resolve, reject) => {
    reject("Oops! Something went wrong.");
});

badPromise.catch((error) => {
    console.log(error);
});

Analogy: If the pizza guy gets lost, at least you know what went wrong!

5. Finalizing with .finally()

.finally() runs whether the Promise is resolved or rejected.

Example:

pizzaPromise
    .then((message) => console.log(message))
    .catch((error) => console.log(error))
    .finally(() => console.log("Pizza order process complete!"));

Analogy: No matter what, you’ll either eat pizza or cry about it—but life goes on.

Conclusion 

Promises help JavaScript handle asynchronous tasks smoothly. Using .then(), .catch(), and .finally(), you can manage async operations effectively. Now, go forth and conquer async programming like a JavaScript ninja!


Post a Comment

0 Comments