Concept Explanation
A Promise is like a I.O.U. (I Owe You). When you start an async task, JavaScript gives you a Promise object immediately. It says: "The task isn't done yet, but I promise to tell you if it Succeeds (Resolved) or Fails (Rejected)."
This changed JS forever because it allowed us to "Chain" tasks linearly instead of nesting them.
Syntax or Core Structure
States of a Promise
- Pending: Working on it...
- Fulfilled: Done! Here is the data.
- Rejected: Error! Something went wrong.
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) resolve("Success!");
else reject("Failed!");
});
myPromise
.then(data => console.log(data)) // "Success!"
.catch(err => console.error(err)) // Handles errors
.finally(() => console.log("Always runs"));
Real World Example
A Bank Transaction:
- You swipe your card (Start Promise).
- The screen says "Authorizing..." (Pending).
- If you have money: "Success" (Resolved).
- If not: "Insufficient Funds" (Rejected).
Best Practices
- Always .catch(): A rejected promise without a
.catch()will crash your app with a "Uncaught Promise Rejection" error. - Promise.all(): If you need to fetch 3 users, start them all and use
Promise.all([p1, p2, p3])to wait for the whole group. It's much faster! - Return your Promises: Inside a
.then()chain, always return the next promise to keep the chain alive.
Practice Exercises
- The Coin Flip: Write a function that returns a Promise. Resolve it if a random number is > 0.5, otherwise reject it.
- The Chain Linker: Create three functions that return promises. Chain them together so they run one after another:
doA().then(doB).then(doC). - The Parallel Race: Use
Promise.race()with two timers (one for 1s, one for 2s) and see which one "wins."