es6

Chapter 6: Mastering JavaScript Promises (ES6) with Real Examples

Chapter 6: Understanding JavaScript Promises (ES6)

In JavaScript, a Promise is a powerful feature introduced in ES6 to manage asynchronous operations more effectively. It provides a cleaner and more structured way to handle tasks that may complete in the future — like loading data from an API, reading files, or waiting for a timer.

🧠 What Is a Promise?

A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to write asynchronous code that is easier to read and manage.

📌 Real-Life Analogy

Imagine you promise your friend that you’ll pay their fees next month. At the time of the promise, you don’t know if you’ll be able to fulfill it — you might succeed, or you might fail. Similarly, in code:

  • Pending: You don’t yet know the result (maybe you’re still trying to arrange the money).
  • Fulfilled: You paid the fees successfully (promise resolved).
  • Rejected: You failed to pay (promise rejected).
  • Settled: Either fulfilled or rejected — the promise is completed.

🔄 Why Use Promises?

  • Improves code readability for asynchronous tasks
  • Eliminates “callback hell”
  • Better error handling using .catch()
  • Allows chaining of multiple asynchronous operations using .then()

🧪 Example 1: Basic Promise with Timeout

This example creates a Promise that resolves after 3 seconds:


let objPromise = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve("Operation Successful!");
  }, 3000);
});

objPromise.then(function(value) {
  document.getElementById("result").innerHTML = value;
});
  

Output: After 3 seconds, “Operation Successful!” is displayed.

✅ Example 2: Promise with Condition (Resolve / Reject)


const x = "acesoftech"; 
const y = "acesoftech";

let objPromise = new Promise(function(resolve, reject) {
  if (x === y) {
    resolve("Success");
  } else {
    reject("Invalid Input");
  }
});

objPromise
  .then(function(message) {
    document.getElementById("result").innerHTML = message;
  })
  .catch(function(error) {
    document.getElementById("result").innerHTML = error;
  });
  

Output: Shows “Success” or “Invalid Input” depending on the condition.

🌐 Example 3: Fetching Data from an API Using Promises

In real-world applications, Promises are heavily used with APIs to fetch data asynchronously:

// Function to fetch data from JSONPlaceholder API
function fetchData() {
  return fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => response.json()); // Convert to JSON
}

// Function to display fetched data
function displayData(data) {
  const outputDiv = document.getElementById('output');
  outputDiv.innerHTML = `<h2>Title: ${data.title}</h2>
                         <p>Body: ${data.body}</p>`;
}

// Event listener to trigger data fetch
document.getElementById('loadDataBtn').addEventListener('click', () => {
  fetchData()
    .then(data => displayData(data))
    .catch(error => {
      document.getElementById('output').innerText = "Error loading data.";
      console.error("Fetch Error:", error);
    });
});

 

🔁 Promise Chain (Chaining .then() Calls)

You can chain multiple asynchronous operations in sequence:


new Promise((resolve, reject) => {
  setTimeout(() => resolve(10), 1000);
})
.then(result => {
  console.log("Step 1:", result);
  return result * 2;
})
.then(result => {
  console.log("Step 2:", result);
  return result * 3;
})
.then(result => {
  console.log("Final Result:", result);
});
  

Output: Logs each step after 1 second. Helps manage sequences in a clean flow.

📘 Assignments: Practice JavaScript Promises

  1. Create a Promise that resolves after 5 seconds with the message “Data Loaded” and display it in a div.
  2. Write a condition-based Promise that checks if a user’s age is 18 or above. Resolve with “Allowed” or reject with “Not Allowed.”
  3. Use fetch() with Promise to get user data from JSONPlaceholder API and display it on button click.
  4. Chain three .then() calls: Multiply a number by 2, then 3, then subtract 5. Log each step.

📌 Summary

  • Promise is an object representing future completion or failure of an async operation.
  • It has three states: pending, fulfilled, and rejected.
  • Use .then() to handle success and .catch() to handle errors.
  • Promises help in writing clean and manageable async code.

Leave a Reply

Your email address will not be published. Required fields are marked *