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 (5)

Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

great, thanks for sharing .

Collapse
 
jagroop2001 profile image
Jagroop Singh

You're welcome! 😊

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
 
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.