DEV Community

Cover image for JavaScript Promises Simplified: Beginner’s Guide with Real-Life Examples πŸš€
Burhanuddin S. Tinwala
Burhanuddin S. Tinwala

Posted on

JavaScript Promises Simplified: Beginner’s Guide with Real-Life Examples πŸš€

What Are Promises in JavaScript?

In JavaScript, a Promise is a powerful tool for managing asynchronous tasks. It’s an object representing a value that might be available now, in the future, or never. Promises make it easier to handle tasks like:

  • Fetching data from an API. 🌐
  • Waiting for a timer to finish. ⏱️
  • Handling user actions, like clicking a button. πŸ–±οΈ

A promise can be in one of these three states:

  1. Pending: The task is ongoing and hasn’t completed yet. ⏳
  2. Fulfilled (Resolved): The task completed successfully. βœ…
  3. Rejected: The task failed. ❌

How Do Promises Work? (Beginner-Friendly Explanation)

Let’s use a cafΓ© analogy:

  • Order Coffee (Pending): You order coffee and wait for it to be prepared. πŸ”„
  • Coffee Ready (Resolved): The barista gives you your coffee. πŸŽ‰
  • Machine Broken (Rejected): The barista tells you the coffee machine is out of order. πŸ˜”

A Simple JavaScript Promise Example

Here’s how you’d write this in JavaScript:

const coffeePromise = new Promise((resolve, reject) => {
  const coffeeReady = true; // Try changing this to false to simulate rejection.

  setTimeout(() => {
    if (coffeeReady) {
      resolve("Your coffee is ready! β˜•");
    } else {
      reject("Sorry, the coffee machine is broken. 😒");
    }
  }, 2000); // Simulates a 2-second wait
});

// Handling the Promise
coffeePromise
  .then((message) => console.log(message)) // If resolved
  .catch((error) => console.error(error)) // If rejected
  .finally(() => console.log("Thanks for visiting our café! 😊"));
Enter fullscreen mode Exit fullscreen mode

Real-Life Examples of Promises in JavaScript

1. Booking a Ride with a Taxi App πŸš—

When you request a ride:

  • Pending: The app searches for a driver. πŸ”„
  • Resolved: A driver accepts your request. βœ…
  • Rejected: No drivers are available. ❌
function bookRide() {
  console.log("Searching for a ride... πŸ”„ (Pending)");

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const driverAvailable = Math.random() > 0.5; // 50% chance of success
      if (driverAvailable) {
        resolve("Driver found! πŸš—πŸ’¨");
      } else {
        reject("No drivers available. πŸ˜”");
      }
    }, 3000); // Simulate search delay
  });
}

// Using the Promise
bookRide()
  .then((message) => {
    console.log("Ride Status: Resolved βœ…");
    console.log(message);
  })
  .catch((error) => {
    console.log("Ride Status: Rejected ❌");
    console.error(error);
  })
  .finally(() => {
    console.log("Thanks for using our ride service! 😊");
  });
Enter fullscreen mode Exit fullscreen mode

2. Downloading a File πŸ“₯

When downloading a file:

  • Pending: The download is in progress. πŸ”„
  • Resolved: The file downloads successfully. βœ…
  • Rejected: The network connection fails. ❌
function downloadFile(fileName) {
  console.log(`Downloading "${fileName}"... πŸ”„ (Pending)`);

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const downloadSuccess = Math.random() > 0.7; // 30% success rate
      if (downloadSuccess) {
        resolve(`"${fileName}" downloaded successfully! πŸ“‚`);
      } else {
        reject(`Failed to download "${fileName}". Check your connection. 🚨`);
      }
    }, 2000); // Simulates download time
  });
}

// Using the Promise
downloadFile("example.pdf")
  .then((message) => {
    console.log("Download Status: Resolved βœ…");
    console.log(message);
  })
  .catch((error) => {
    console.log("Download Status: Rejected ❌");
    console.error(error);
  })
  .finally(() => {
    console.log("Thanks for using our download manager! πŸ“₯");
  });
Enter fullscreen mode Exit fullscreen mode

Example 3: Planning a Road Trip πŸ›€οΈ

When planning a trip, the steps are as follows:

  1. Pack your bags. πŸŽ’
  2. Book a cab. πŸš•
  3. Reach your destination. πŸ–οΈ

Each step can be Pending, Resolved, or Rejected.

function packBags() {
  console.log("Packing bags... πŸ”„ (Pending)");

  return new Promise((resolve) => {
    setTimeout(() => resolve("Bags packed! πŸŽ’ βœ…"), 1000);
  });
}

function bookCab() {
  console.log("Booking a cab... πŸ”„ (Pending)");

  return new Promise((resolve, reject) => {
    const cabAvailable = Math.random() > 0.4; // 60% chance of success
    setTimeout(() => {
      if (cabAvailable) {
        resolve("Cab booked! πŸš• βœ…");
      } else {
        reject("No cabs available. πŸ˜” ❌");
      }
    }, 2000);
  });
}

function reachDestination() {
  console.log("Heading to destination... πŸ”„ (Pending)");

  return new Promise((resolve) => {
    setTimeout(() => resolve("Reached destination! πŸ–οΈ βœ…"), 3000);
  });
}

// Chaining Promises
packBags()
  .then((message) => {
    console.log("Step 1: Resolved βœ…");
    console.log(message);
    return bookCab();
  })
  .then((message) => {
    console.log("Step 2: Resolved βœ…");
    console.log(message);
    return reachDestination();
  })
  .then((message) => {
    console.log("Step 3: Resolved βœ…");
    console.log(message);
  })
  .catch((error) => {
    console.log("Status: Rejected ❌");
    console.error(error);
  })
  .finally(() => {
    console.log("Trip preparation done. Safe travels! πŸš€");
  });

Enter fullscreen mode Exit fullscreen mode

Why Use Promises in JavaScript?

Promises solve a common problem in JavaScript: Callback Hell (nested callbacks that make your code hard to read and debug).

Benefits of Using Promises:

  1. 🌟 Readable Code: Promises make your code easier to understand by avoiding deeply nested callbacks.
  2. 🚨 Error Handling: Manage both success and failure scenarios in one flow.
  3. πŸ”— Chaining: Chain multiple asynchronous tasks together for a clean workflow.

Final Thoughts on JavaScript Promises

Promises are a game-changer for managing asynchronous tasks in JavaScript. Whether you’re booking a ride, downloading a file, or streaming a movie, promises let your code handle these tasks elegantly and efficiently.

Have questions? Drop a comment below! Let’s master JavaScript together. πŸ’¬

Let's connect LinkedIn

Top comments (0)