Understanding JavaScript Promise

Promises in JavaScript are used to handle asynchronous operations. Let’s walk through what they are and test some examples live.

πŸ“˜ Basic Promise Example

This promise resolves after 2 seconds:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("βœ… Promise resolved!");
  }, 2000);
});

promise.then(result => console.log(result));

❌ Promise Rejection Example

Here’s a Promise that rejects when something goes wrong:

const errorPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("❌ Something went wrong");
  }, 1500);
});

errorPromise
  .then(data => console.log(data))
  .catch(error => console.error(error));

πŸš€ Real Use Case: Fetching Data

Let’s simulate fetching user data:

function fetchUserData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ name: "John Doe", age: 30 });
    }, 1000);
  });
}

fetchUserData().then(user => console.log(user));

✨ Try modifying the delays or values in the code to understand how Promises behave!

Share via
Copy link