
Hey there, JavaScript enthusiasts! 👋 Are you ready to dive intoPromises and make your async code cleaner and more fun? 🎉 Let’s break it down step-by-step with simple examples, fewer boring theories, and loads of practical code snippets! 💻✨
What’s a Promise? 🤔
APromise in JavaScript is like a "promise" in real life:
- Pending: "I'll do this later."
- Fulfilled: "I did it!" 🎉
- Rejected: "Oops, something went wrong." 😢
Why Use Promises? 🙋♀️
Before Promises, we hadcallbacks, which often led tocallback hell:
getData(function(data){processData(data,function(result){saveData(result,function(response){console.log("All done!");});});});
😵Hard to read, right?
Promises save the day! 🦸♂️ They flatten this mess into a chain:
getData().then(processData).then(saveData).then(()=>console.log("All done!")).catch((error)=>console.error("Something went wrong:",error));
Let's Build a Promise 🌟
Here’s how you create a promise:
constmyPromise=newPromise((resolve,reject)=>{constsuccess=true;// Change this to false to see rejectionif(success){resolve("Yay! It worked! 🎉");}else{reject("Oh no! Something went wrong. 😢");}});
Using the promise:
myPromise.then((message)=>console.log(message)).catch((error)=>console.error(error));
Real-Life Example: Fetching Data 🛒
Promises are everywhere in JavaScript! A common one isfetch
.
Let’s get some user data:
fetch("https://jsonplaceholder.typicode.com/users/1").then((response)=>response.json())// Convert response to JSON.then((data)=>console.log("User data:",data))// Log the data.catch((error)=>console.error("Error fetching data:",error));// Handle errors
Chaining Promises 🔗
You can chain.then
for multiple steps:
fetch("https://jsonplaceholder.typicode.com/posts/1").then((response)=>response.json()).then((post)=>{console.log("Post Title:",post.title);returnfetch(`https://jsonplaceholder.typicode.com/users/${post.userId}`);}).then((response)=>response.json()).then((user)=>console.log("Author:",user.name)).catch((error)=>console.error("Something went wrong:",error));
Handling Errors 🛑
The.catch
block handles any error in the chain:
fetch("https://jagroopurl.com")// BTW This doesn't exist.then((response)=>response.json()).catch((error)=>console.error("Oops, error caught here:",error));
Pro tip: Add a.catch
at the end of every chain to avoid unhandled errors. 🚨
Parallel Promises withPromise.all
🕒
Run multiple promises in parallel:
constpromise1=fetch("https://jsonplaceholder.typicode.com/posts/1");constpromise2=fetch("https://jsonplaceholder.typicode.com/posts/2");Promise.all([promise1,promise2]).then((responses)=>Promise.all(responses.map((r)=>r.json()))).then((data)=>console.log("Both posts:",data)).catch((error)=>console.error("One or more promises failed:",error));
A Promise-Based Timer ⏳
Let's create a timer using promises:
constwait=(ms)=>newPromise((resolve)=>setTimeout(resolve,ms));wait(2000).then(()=>console.log("2 seconds later... ⏰"));
Let's Test Your Knowledge! 🧠
Here’s a tricky question for you:
constpromise=newPromise((resolve,reject)=>{console.log("1. Promise created");resolve("2. Promise resolved");});promise.then((msg)=>console.log(msg));console.log("3. Synchronous log");
What will be the output? 🤔
Your Turn! 🎤
Did this make Promises less intimidating? 😄 Try out the examples, tweak them, and share your answers to the tricky question in the comments below! 👇
Happy coding! 🚀
Top comments(13)

I would also add that while using promise.all could speedup things, it still runs in the same thread, many people don't realize this and end up wondering why their code is slow.

- Email
- LocationIndia
- EducationBachelor of Technology (Computer Science & Engineering)
- PronounsHe/Him
- WorkTech Lead ( Software Engineer)
- Joined
Yes ,but I think it's okay.
At some situations speed matters and in some situations resources consumed.

I'm not sure if it's ok that 90 procent of the devs out there think Promise.all runs multiple threads

- Email
- LocationIndia
- EducationBachelor of Technology (Computer Science & Engineering)
- PronounsHe/Him
- WorkTech Lead ( Software Engineer)
- Joined
🤣, soooo true.

- Email
- LocationDhaka, Bangladesh
- EducationB.Sc. in Computer Science Engineering
- PronounsMr.
- WorkCurrently, I’m focused on problem-solving and learning DSA while freelancing.
- Joined
great, thanks for sharing .

- Email
- LocationIndia
- EducationBachelor of Technology (Computer Science & Engineering)
- PronounsHe/Him
- WorkTech Lead ( Software Engineer)
- Joined
You're welcome! 😊

- Email
- LocationIndia
- EducationBachelor of Technology (Computer Science & Engineering)
- PronounsHe/Him
- WorkTech Lead ( Software Engineer)
- Joined
Absolutely correct !!@_aliraza ,
I hope you know the reason for this.

- Email
- LocationIndia
- EducationBachelor of Technology (Computer Science & Engineering)
- PronounsHe/Him
- WorkTech Lead ( Software Engineer)
- Joined
Let me know what’s missing—your feedback can make it even better! 😊
Some comments may only be visible to logged-in visitors.Sign in to view all comments.
For further actions, you may consider blocking this person and/orreporting abuse