May 6, 2023

JavaScript Promise

1. What is a Promise?

A Promise is a JavaScript object that represents the future result of an asynchronous operation.
It allows you to write asynchronous code in a cleaner and more manageable way.

  • It can be:
    • Pending – still running
    • Fulfilled – completed successfully
    • Rejected – failed with an error

2. Why are Promises useful?

Promises help us avoid callback hell and make async code easier to read and maintain.


3. Basic syntax

const myPromise = new Promise((resolve, reject) => {
  if (/* success */) {
    resolve("Success!");
  } else {
    reject("Error!");
  }
});

4. How to use .then() and .catch()

myPromise
  .then((result) => {
    console.log("Resolved:", result);
  })
  .catch((error) => {
    console.error("Rejected:", error);
  });
  • .then() is used when the promise is successful
  • .catch() is used when the promise fails

5. What is async/await?

async/await is a modern way to work with Promises using a more readable syntax.

const fetchData = async () => {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Fetch error:", error);
  }
};
  • async makes the function return a Promise
  • await pauses the function until the Promise resolves
  • Use try...catch for error handling

6. Common interview questions and sample answers

❓ Q: What are the three states of a Promise?

✅ A: Pending, Fulfilled, and Rejected.


❓ Q: What is the difference between callbacks and Promises?

✅ A: Promises provide a cleaner way to handle async code and avoid nested callback structures (callback hell).


❓ Q: How does async/await relate to Promises?

✅ A: async/await is built on top of Promises. It makes Promise-based code look synchronous and easier to read.


❓ Q: How do you handle errors in Promises?

✅ A: Use .catch() or wrap the code in a try...catch block if using async/await