Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Let's Learn Promises in JavaScript! 🚀
Jagroop Singh
Jagroop Singh

Posted on

     

Let's Learn Promises in JavaScript! 🚀

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!");});});});
Enter fullscreen modeExit fullscreen mode

😵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));
Enter fullscreen modeExit fullscreen mode

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. 😢");}});
Enter fullscreen modeExit fullscreen mode

Using the promise:

myPromise.then((message)=>console.log(message)).catch((error)=>console.error(error));
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

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));
Enter fullscreen modeExit fullscreen mode

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));
Enter fullscreen modeExit fullscreen mode

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));
Enter fullscreen modeExit fullscreen mode

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... ⏰"));
Enter fullscreen modeExit fullscreen mode

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");
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
vandeurenglenn profile image
Glenn Vandeuren
  • Joined

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.

CollapseExpand
 
jagroop2001 profile image
Jagroop Singh
👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views
  • Email
  • Location
    India
  • Education
    Bachelor of Technology (Computer Science & Engineering)
  • Pronouns
    He/Him
  • Work
    Tech Lead ( Software Engineer)
  • Joined

Yes ,but I think it's okay.
At some situations speed matters and in some situations resources consumed.

CollapseExpand
 
vandeurenglenn profile image
Glenn Vandeuren
  • Joined

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

Thread Thread
 
jagroop2001 profile image
Jagroop Singh
👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views
  • Email
  • Location
    India
  • Education
    Bachelor of Technology (Computer Science & Engineering)
  • Pronouns
    He/Him
  • Work
    Tech Lead ( Software Engineer)
  • Joined

🤣, soooo true.

CollapseExpand
 
charles-22 profile image
Charles Jordan
  • Joined

Yes I agree with you.

CollapseExpand
 
john12 profile image
john
  • Joined

WoW !! This is a Gem.
I really liked your javascript series.

CollapseExpand
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam
I am a Full-Stack Developer specialized Front-end Developer. Passionate about algorithms, data structures, and coding challenges & always ready to face new challenges.
  • Email
  • Location
    Dhaka, Bangladesh
  • Education
    B.Sc. in Computer Science Engineering
  • Pronouns
    Mr.
  • Work
    Currently, I’m focused on problem-solving and learning DSA while freelancing.
  • Joined

great, thanks for sharing .

CollapseExpand
 
jagroop2001 profile image
Jagroop Singh
👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views
  • Email
  • Location
    India
  • Education
    Bachelor of Technology (Computer Science & Engineering)
  • Pronouns
    He/Him
  • Work
    Tech Lead ( Software Engineer)
  • Joined

You're welcome! 😊

CollapseExpand
 
_aliraza profile image
Ali Raza
I'm not a robot
  • Location
    Faisalabad, Punjab, Pakistan
  • Joined

log:
1
3
2

Thanks for the nice article 🎉

CollapseExpand
 
jagroop2001 profile image
Jagroop Singh
👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views
  • Email
  • Location
    India
  • Education
    Bachelor of Technology (Computer Science & Engineering)
  • Pronouns
    He/Him
  • Work
    Tech Lead ( Software Engineer)
  • Joined

Absolutely correct !!@_aliraza ,
I hope you know the reason for this.

CollapseExpand
 
rmsilva1973 profile image
Renato Silva
  • Joined

I Promise people won't find a better article on the subject. 😂

CollapseExpand
 
jagroop2001 profile image
Jagroop Singh
👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views
  • Email
  • Location
    India
  • Education
    Bachelor of Technology (Computer Science & Engineering)
  • Pronouns
    He/Him
  • Work
    Tech Lead ( Software Engineer)
  • Joined

Let me know what’s missing—your feedback can make it even better! 😊

CollapseExpand
 
matikiri profile image
Matikiri
matikiri
  • Location
    Seoul
  • Work
    matikiri at matikiri
  • Joined

Oke

Some comments may only be visible to logged-in visitors.Sign in to view all comments.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views
  • Location
    India
  • Education
    Bachelor of Technology (Computer Science & Engineering)
  • Pronouns
    He/Him
  • Work
    Tech Lead ( Software Engineer)
  • Joined

More fromJagroop Singh

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp