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)