SmartCodingTips

πŸ“¦ JavaScript Promises

A Promise is a special JavaScript object that represents a value that may be available now, later, or never. It’s a cleaner alternative to deeply nested callbacks and is commonly used for asynchronous operations like API requests.

πŸ› οΈ Creating a Promise

const myPromise = new Promise((resolve, reject) => {
  const success = true;

  if (success) {
    resolve("βœ… Success!");
  } else {
    reject("❌ Failed!");
  }
});

πŸ”— Consuming a Promise

myPromise
  .then(result => console.log(result))   // Success handler
  .catch(error => console.error(error)) // Error handler
  .finally(() => console.log("Done!")); // Always runs

⏳ Real Example: Simulate API Delay

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("πŸ“‘ Data received after 2 seconds");
    }, 2000);
  });
}

fetchData().then(data => console.log(data));

πŸ”„ Promise States

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

πŸ” Chaining Promises

fetchUser()
  .then(user => fetchPosts(user.id))
  .then(posts => fetchComments(posts[0].id))
  .then(comments => console.log(comments))
  .catch(error => console.error("Error:", error));
πŸ’‘ Tip: Promises allow you to write async logic in a more structured and maintainable way.