Promise vs Observables

Mohammad Farman Abbasi
4 min readJan 5, 2024

Promises:

  1. Single Value: Promises are designed to handle a single asynchronous result. Once the promise is resolved or rejected, it cannot be reused for another value.
  2. Eager Execution: Promises are eager, meaning they start executing as soon as they are created. This can lead to issues if not handled properly.
  3. Error Handling: Promises have a simple error-handling mechanism through the .catch() method.
  4. No Cancellation: Promises don’t support cancellation. Once a promise is initiated, it will eventually resolve or reject, and there’s no built-in mechanism to cancel it.

Example:

const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation
if (/* operation is successful */) {
resolve(result);
} else {
reject(error);
}
});
myPromise.then(result => {
// Handle successful result
}).catch(error => {
// Handle error
});

Observables:

  1. Multiple Values Over Time: Observables are more powerful and flexible than promises. They can handle multiple values over time, making them suitable for handling streams of data.
  2. Lazy Execution: Observables are lazy, meaning they don’t execute until you subscribe to them. This allows you to set up complex chains of operations before they start.
  3. Advanced Error Handling: Observables provide more advanced error-handling mechanisms through the .catch(), .retry(), and other operators.
  4. Cancellation: Observables support cancellation through unsubscribing. If you’re no longer interested in the result or data stream, you can unsubscribe to stop the ongoing operations.

Example:

import { Observable } from 'rxjs';
const myObservable = new Observable(observer => {
// Asynchronous operation
if (/* operation is successful */) {
observer.next(result);
observer.complete();
} else {
observer.error(error);
}
});
const subscription = myObservable.subscribe(
result => {
// Handle successful result
},
error => {
// Handle error
},
() => {
// Handle completion
}
);
// To unsubscribe and cancel the observable
subscription.unsubscribe();

While promises are simpler and sufficient for handling simple asynchronous operations, observables provide more powerful features for handling complex scenarios, especially when dealing with streams of data over time. Angular itself heavily uses observables, particularly through the use of the RxJS library.

Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time.

Subjects are observables themselves but what sets them apart is that they are also observers.

subject can emit data, on top of having the capability to be subscribed to.

let subject = new Subject<string>();

// We subscribe to the subject

subject.subscribe((data) => {

console.log(“Subscriber got data >>>>> “+ data);

});

// We use the subject to emit data

subject.next(“Eureka”);

// Console result: Subscriber got data >>>>> Eureka

A regular observable does not have the next() method as regular observables are not observers. So that the first super power of a subject: Data emission.

Subjects are multicast

The second super power of subjects is that they support multiple subscriptions. In other words, they are multicast.

Subjects are like EventEmitters: They maintain a registry of many listeners.

let subject = new Subject<string>();

subject.subscribe((data) => {

console.log(“Subscriber 1 got data >>>>> “+ data);

});

subject.subscribe((data) => {

console.log(“Subscriber 2 got data >>>>> “+ data);

});

subject.next(“Eureka”);

// Console result:

// Subscriber 1 got data >>>>> Eureka

// Subscriber 2 got data >>>>> Eureka

As a result, you can use a Subject in a service to fetch some data, and send the result to all components that subscribed to that Subject.

There is one thing I would recommend though: Do not expose the Subject object directly to your components. Instead, return a good old Observable version of it:

// Don’t do that or you subscribers will be able to “mess” with your // subject

getData(): Subject<Data> {

return this.subject;

}

// Do this instead:

getData(): Observable<Data> {

return this.subject.asObservable();

}

The above will make your code much safer and will prevent poor coding practices.

Behavior Subjects

Behavior Subjects are another cool thing about subjects. When you subscribe to a behavior subject, it will give you the last emitted value right away.

Imagine subscribing to a magazine, and right away you receive the latest published issue of it. Wouldn�t that be awesome? Welcome to the world of behavior subjects!

// Behavior subjects need a first value

let subject = new BehaviorSubject<string>(“First value”);

subject.asObservable().subscribe((data) => {

console.log(“First subscriber got data >>>>> “+ data);

});

subject.next(“Second value”)

// Console result:

// First subscriber got data >>>>> First value

// First subscriber got data >>>>> Second value

With behavior subjects, it does not matter when you subscribe, you always get the latest value right away, which can be very useful.

Now what if we want more than just the latest emitted value?

Replay Subjects

Replay Subjects keep a given number of historical values so that those values can be replayed to new subscribers.

// We tell the ReplaySubject how many values should be kept in // history

let subject = new ReplaySubject<string>(2);

subject.next(“First value”);

subject.next(“Second value”);

subject.next(“Third value”);

subject.asObservable().subscribe((data) => {

console.log(“First subscriber got data >>>>> “+ data);

});

subject.next(“Fourth value”);

//Console result:

// First subscriber got data >>>>> Second value

// First subscriber got data >>>>> Third value

// First subscriber got data >>>>> Fourth value

In the above example, my Replay Subject keeps a history length of two values. As a result, as a soon as a new subscriber comes up, it gets the last two values, as well as any new value that comes up later on.

As you can see, Subjects are a very interesting� subject (that was easy!). We just scratched the surface of what they can accomplish, feel free to let me know if you�d like a follow up article with a deeper dive into what they can do.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Mohammad Farman Abbasi
Mohammad Farman Abbasi

Written by Mohammad Farman Abbasi

Learning each day without giving up.

No responses yet

Write a response