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 into Promises 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? πŸ€”

A Promise 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 had callbacks, which often led to callback hell:

getData(function (data) {
  processData(data, function (result) {
    saveData(result, function (response) {
      console.log("All done!");
    });
  });
});
Enter fullscreen mode Exit 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 mode Exit fullscreen mode

Let's Build a Promise 🌟

Here’s how you create a promise:

const myPromise = new Promise((resolve, reject) => {
  const success = true; // Change this to false to see rejection
  if (success) {
    resolve("Yay! It worked! πŸŽ‰");
  } else {
    reject("Oh no! Something went wrong. 😒");
  }
});
Enter fullscreen mode Exit fullscreen mode

Using the promise:

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

Real-Life Example: Fetching Data πŸ›’

Promises are everywhere in JavaScript! A common one is fetch.

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 mode Exit 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);
    return fetch(`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 mode Exit 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 mode Exit fullscreen mode

Pro tip: Add a .catch at the end of every chain to avoid unhandled errors. 🚨


Parallel Promises with Promise.all πŸ•’

Run multiple promises in parallel:

const promise1 = fetch("https://jsonplaceholder.typicode.com/posts/1");
const promise2 = 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 mode Exit fullscreen mode

A Promise-Based Timer ⏳

Let's create a timer using promises:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

wait(2000).then(() => console.log("2 seconds later... ⏰"));
Enter fullscreen mode Exit fullscreen mode

Let's Test Your Knowledge! 🧠

Here’s a tricky question for you:

const promise = new Promise((resolve, reject) => {
  console.log("1. Promise created");
  resolve("2. Promise resolved");
});

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

console.log("3. Synchronous log");
Enter fullscreen mode Exit 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)

Collapse
 
vandeurenglenn profile image
Glenn Vandeuren

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.

Collapse
 
jagroop2001 profile image
Jagroop Singh

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

Collapse
 
vandeurenglenn profile image
Glenn Vandeuren

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

🀣, soooo true.

Collapse
 
charles-22 profile image
Charles Jordan

Yes I agree with you.

Collapse
 
_aliraza profile image
Ali Raza

log:
1
3
2

Thanks for the nice article πŸŽ‰

Collapse
 
jagroop2001 profile image
Jagroop Singh

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

Collapse
 
matikiri profile image
Matikiri

Oke

Collapse
 
john12 profile image
john

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

Collapse
 
rmsilva1973 profile image
Renato Silva

I Promise people won't find a better article on the subject. πŸ˜‚

Collapse
 
jagroop2001 profile image
Jagroop Singh

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

Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

great, thanks for sharing .

Collapse
 
jagroop2001 profile image
Jagroop Singh

You're welcome! 😊

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