Angular: Observable v/s Promise

ankushgoyal11

Ankush Goyal

Posted on November 27, 2024

Angular: Observable v/s Promise

Observables and Promises are both used to handle asynchronous operations in JavaScript, but they have some key differences:

Promises

  • Single Value: Promises handle a single asynchronous event and return a single value (or error).
  • Eager: Promises start executing immediately upon creation.
  • Not Cancellable: Once a Promise is initiated, it cannot be cancelled.
  • Syntax: Uses .then(), .catch(), and .finally() for chaining operations.

Example:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise resolved!');
  }, 1000);
});

promise.then((value) => {
  console.log(value);
});
Enter fullscreen mode Exit fullscreen mode

Observables

  • Multiple Values: Observables can emit multiple values over time.
  • Lazy: Observables do not start emitting values until they are subscribed to.
  • Cancellable: Subscriptions to Observables can be cancelled, stopping the emission of values.
  • Syntax: Uses .subscribe() to handle emitted values, errors, and completion.

Example:

import { Observable } from 'rxjs';

const observable = new Observable((subscriber) => {
  subscriber.next('First value');
  setTimeout(() => {
    subscriber.next('Second value');
    subscriber.complete();
  }, 1000);
});

const subscription = observable.subscribe({
  next(value) {
    console.log(value);
  },
  complete() {
    console.log('Observable complete');
  }
});

// To cancel the subscription
subscription.unsubscribe();
Enter fullscreen mode Exit fullscreen mode

When to Use Each

  • Use Promises when you need to handle a single asynchronous operation.
  • Use Observables when you need to handle multiple asynchronous events or values over time, and when you need more control over the data stream (e.g., cancellation, transformation).

Thank you for reading!
I hope you found this article helpful and informative. If you enjoyed it or learned something new, feel free to share your thoughts in the comments or connect with me.

If you'd like to support my work and help me create more content like this, consider buying me a coffee. Your support means the world and keeps me motivated!

Thanks again for stopping by! 😊

Buy Me A Coffee

πŸ’– πŸ’ͺ πŸ™… 🚩
ankushgoyal11
Ankush Goyal

Posted on November 27, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related