Understanding JavaScript Promises: Pending, Resolve, Reject

Ever wondered what a Promise is in JavaScript? It's basically like a placeholder for something that's happening in the background—like waiting for your food delivery. You don't know exactly when it'll arrive, but once it does, you get the goods (success) or find out it got lost (error). Here's the simple breakdown: A Promise starts in "pending" mode. Then it either: Resolves (yay! data's here 🎉) Or rejects (oops, something broke ❌) You create one like this: const myPromise = new Promise((resolve, reject) => { setTimeout(() => { if (Math.random() > 0.5) { resolve("Success! Here's your data."); } else { reject("Sorry, failed."); } }, 1000); }); Handle it with .then() for wins, .catch() for fails: myPromise .then(result => console.log(result)) .catch(error => console.log(error)); Chain them to avoid callback hell—super clean for real-world apps like fetching APIs. Promises power async JS. #JavaScript #Promises #WebDev

To view or add a comment, sign in

Explore content categories