DEV Community

Cover image for Promises Vs Observables: Decoding JavaScript's Asynchronous Superheroes!
Prince Takyi Akomea
Prince Takyi Akomea

Posted on

Promises Vs Observables: Decoding JavaScript's Asynchronous Superheroes!

Today, we're taking a fascinating dive into the world of JavaScript, specifically focusing on two vital concepts – Promises and Observables. Now, let's first set something straight – both observables and promises are fantastic tools for managing asynchronous code in JavaScript. But these two seemingly similar tools have some important differences you need to be aware of, and that's what we're here to explore. So buckle up, here’s a friendly guide to differentiate between observables and promises.

Firstly, the definitions! When dealing with asynchronous operations, a Promise is an object that may produce a single value some time in the future, either a resolved value or a reason why it’s not resolved (er, yes, the dreaded error!). On the other hand, Observable is not so much about future values but rather is a stream of many values over a period of time. 

So to break it down,

  • Promise = Potential future single value

  • Observable = Many values over time (known as a stream)

Let’s go a bit deeper here. Consider a Promise to be a one-time coupon. It’s either redeemed successfully (resolved), or it fails to be cashed in (rejected). But no matter what, it’s a one-time deal--you can't use the same coupon code again.  

Similarly, Promises wrap asynchronous tasks in a redeemable coupon and deliver the result once the task is complete.

Here's a simple example:

const promiseExample = new Promise((resolve, reject) => {
  // Simulating an asynchronous action
  setTimeout(() => {
    const result = Math.random();
    if (result > 0.5) {
      resolve(`Success! Value: ${result}`);
    } else {
      reject(`Error! Value: ${result}`);
    }
  }, 1000);
});

promiseExample
  .then(result => console.log(result))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

On the flip side, imagine an Observable like a concert where your favourite band is performing. This concert (or stream) continues for a period of time and throughout the concert, the band keeps serving hit songs (values). You can enjoy the performance (subscribe👍) the entire time it lasts, and leave anytime you wish (unsubscribe👎).

The important part here is that Observables support cancellation. If an Observable is an ongoing concert, you can leave (or cancel) anytime, and no more songs (values) are delivered. But on the contrary, a Promise is a one-time event; once it gets started, it will deliver a value whether you want it or not.

import { Observable } from 'rxjs';

const observableExample = new Observable(observer => {
  // Emitting data at intervals
  const intervalId = setInterval(() => {
    const data = Math.random();
    if (data > 0.5) {
      observer.next(`Data: ${data}`);
    } else {
      observer.error(`Error: ${data}`);
    }
  }, 1000);

  // Cleanup logic when unsubscribed
  return () => {
    clearInterval(intervalId);
  };
});

const subscription = observableExample.subscribe(
  data => console.log(data),
  error => console.error(error),
  () => console.log('Observable completed')
);

// Unsubscribe after a certain time
setTimeout(() => {
  subscription.unsubscribe();
}, 5000);

Enter fullscreen mode Exit fullscreen mode

Another key difference lies in their treatment of error conditions. Promises will automatically transition to a rejected state upon any uncaught error thrown in resolve. Observables, however, are far more forgiving. Unless there is a subscription to error, the Observable stream can continue broadcasting values.

The Distinctive Pathways

So, which one should you use? Well, it depends! If you want to handle a single async call and don't need cancellation, go for Promise. But if you want a sequence of values over time and want flexibility with error handling and cancellation, Observable is the way to go.

Remember, coding is all about using the right tool for the job. Promises and Observables are different tools, designed for different jobs in the asynchronous world of JavaScript.

Next time you're faced with an asynchronous task in JavaScript, remember our little talk about the concert and the coupon. Decide what fits your scenario and play the right tune.

Conclusion

In the ever-evolving world of JavaScript, Promises and Observables are significant tools to manage asynchronous code. While Promises are perfect for one-time asynchronous events, Observables offer flexibility in dealing with multiple values over any duration of time. Now that you know the differences, it's time to put these tools into action. Happy coding folks!

Top comments (0)