JavaScript Promises
Alpi Tek JavaScript Promises

🌟 Learn JavaScript Promises with Easy Examples

Spread the love

⁉️What Are JavaScript Promises? Explained with Simple Examples for Beginners

In modern web development, dealing with asynchronous operations is a mustβ€”whether it’s fetching data from a server or performing a long-running task in the background. That’s where JavaScript Promises come in.

In this blog post, we’ll explore JavaScript Promises in simple terms, using real-world analogies and beginner-friendly code examples.


πŸ€” What is a Promise?

A Promise is a JavaScript object that represents the eventual result of an asynchronous operation. It can either:

  • βœ… Resolve successfully with a value
  • ❌ Reject with an error

Think of it like ordering food: you place an order and receive a “promise” that your meal will arrive. Eventually, the restaurant either brings your food or tells you it’s not available.


πŸ”§ How to Create a Promise

Here’s the basic syntax:

javascriptCopyEditlet promise = new Promise(function(resolve, reject) {
  // Perform async task
  if (/* success condition */) {
    resolve("Success!");
  } else {
    reject("Failure!");
  }
});

You handle the result using .then() and .catch():

javascriptCopyEditpromise
  .then(result => {
    console.log("Resolved:", result);
  })
  .catch(error => {
    console.log("Rejected:", error);
  });

βœ… Example 1: Cleaning a Room

javascriptCopyEditlet cleanRoom = new Promise(function(resolve, reject) {
  let isClean = true;

  if (isClean) {
    resolve("The room is clean!");
  } else {
    reject("The room is messy...");
  }
});

cleanRoom
  .then(function(message) {
    console.log("Promise resolved:", message);
  })
  .catch(function(error) {
    console.log("Promise rejected:", error);
  });

Output:

csharpCopyEditPromise resolved: The room is clean!

🌐 Example 2: Simulating a Network Request

javascriptCopyEditfunction fetchData() {
  return new Promise((resolve, reject) => {
    console.log("Fetching data...");
    setTimeout(() => {
      let success = true;

      if (success) {
        resolve({ user: "Alice", age: 25 });
      } else {
        reject("Failed to fetch data");
      }
    }, 2000);
  });
}

fetchData()
  .then(data => {
    console.log("Data received:", data);
  })
  .catch(error => {
    console.log("Error:", error);
  });

Output:

cssCopyEditFetching data...
Data received: { user: 'Alice', age: 25 }

πŸ” Chaining Promises

You can chain multiple .then() calls to perform sequential actions:

javascriptCopyEditfetchData()
  .then(data => {
    console.log("User:", data.user);
    return data.age;
  })
  .then(age => {
    console.log("Age:", age);
  })
  .catch(error => {
    console.log("Error:", error);
  });

πŸ“Š Promise States

A Promise can be in one of three states:

  1. Pending – still waiting
  2. Fulfilled – operation completed successfully
  3. Rejected – operation failed

Once fulfilled or rejected, the state is final and can’t change again.


πŸ“Œ Summary

Here’s a quick overview:

TermDescription
resolve()Call this when the operation succeeds
reject()Call this when the operation fails
.then()Handles the success result
.catch()Handles any error or rejection