Angular Observable VS. Promise

Muhammad Adil Feb 11, 2022
  1. What Is Promise in Angular
  2. What Is Observable in Angular
  3. Key Differences Between Promise and Observable in Angular
Angular Observable VS. Promise

Angular is a framework for building web applications. Angular has two main types of data management: observables and promises.

Observables and Promises implementations make it easier for us to cope with asynchronous programs, and they use separate APIs and have slightly different motives.

This article will explain what is Observable and Promise in Angular. Moreover, we will explain the fundamental difference between Observable and Promise.

What Is Promise in Angular

Promises are a JavaScript construct that provides a way to handle asynchronous operations. They represent an eventual result of an asynchronous operation and can be in one of three states: pending, fulfilled, or rejected.

Promises can also be chained together to represent a series of dependent asynchronous operations.

Moreover, a Promise is a type of object that can produce a single value in the future, either a resolved value or a reason why it can’t be resolved, or it can be pending.

If you’re still stumped, apply this to a real-life situation. If you make a promise to a friend, you must either fulfill the Promise or reject it; yet, there are times when you are trapped in the middle, attempting to fulfill the Promise but failing to do so.

Similarly, a Promise in programming can also work on the same procedure.

Promise’s drawbacks include:

  1. A failed call could not be retried.
  2. Promises become more difficult to manage as our application grows.
  3. The user could not cancel a request to the API.

What Is Observable in Angular

What exactly are observables in Angular? It can be compared to a Promise in its most basic form, and it has a single value over time.

Observables, on the other hand, are considerably more than that. Angular Observables are more powerful than Promises because it has many advantages such as better performance and easier debugging.

An Observable can supply many values over time, similar to how streaming works, and it can be quickly terminated or retried if there are any errors. Observables can be coupled in various ways, or there might be a competition to see who can use the first one.

The RxJS Observables library is a powerful tool. Moreover, they are like event emitters that can emit unlimited values over time.

Draw Backs:

  1. You have to acquire a complicated framework of observable.
  2. You may find yourself using Observables in unexpected situations.

Key Differences Between Promise and Observable in Angular

Let’s discuss some of the differences between Promise and Observable.

Promise Observable
Once a promise is fulfilled, its value does not alter. They are limited to emitting, rejecting and resolving a single value. Multiple values can be emitted over some time using observables. It helps retrieve multiple values at once.
Lazy Loading does not apply to promises. So, Promises are immediately applied whenever they are formed. Observables don’t start executing until they’re subscribed. This makes Observables handy whenever an action is required.
Instead of handling errors directly, Angular Promises always pass errors on to the child’s promises. Error handling is the responsibility of Angular Observables. When we utilize Observables, we can handle all errors in a single spot.
You can’t back out of a promise once you’ve started it. The promise will be resolved or rejected based on the callback provided to the Promise. With the help of the unsubscribe method, you can cancel observables at any time.

Example of Promise and Observable in Angular

Let’s discuss an example that helps us understand the concept of promise and observable in detail.

Typescript Code:

import { Component } from '@angular/core';
import { Observable, Observer, } from "rxjs";

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    promiseTemp: Promise<boolean>;
  createPromise() {
    this.promiseTemp = this.testPromise(0);
  }
  observableTemp: Observable<boolean>;

  createObservable() {
    this.observableTemp = this.testObservable(0);
  }

  subscribeObservable() {
    this.observableTemp
      .subscribe(
        result => {
          console.log(`Observable Ok: ${result}`);
        },
        err => {
          console.error(err);
        });
  }
  observableNextTemp: Observable<boolean>;
  createObservableNext() {
    this.observableNextTemp = this.testObservableNext(0);
  }
  promiseTemp2: Promise<boolean>;
  createToPromiseByObservable() {
    this.promiseTemp2 = this.testObservable(0).toPromise();
  }
  observableForkJoinTemp: Observable<boolean[]>;
  countForkJoin = 2;

  testObservable(value: number): Observable<boolean> {
    console.log("create Observable");
    return Observable.create((observer: Observer<boolean>) => {
      console.log("execute Observable");
      this.testPromise2(value)
        .then(result => {
          observer.next(result);
          observer.complete();
        })
        .catch(err => {
          observer.error(err);
          observer.complete();
        });
    });
  }

  testObservableNext(value: number): Observable<boolean> {
    console.log("create Observable Next");
    return Observable.create((observer: Observer<boolean>) => {
      console.log("execute Observable Next");
      this.testPromise2(value)
        .then(result => {
          observer.next(result);

          setTimeout(() => {
            observer.next(result);
            observer.complete();
          }, 5000);

        })
        .catch(err => {
          observer.error(err)
        });
    });
  }

  testPromise(value: number): Promise<boolean> {
    console.log("creation");
    return new Promise((resolve, reject) => {
      console.log("execution");
      this.testPromise2(value)
        .then(result => {
          resolve(result);
        })
        .catch(reject);
    });
  }

  testPromise2(value: number): Promise<boolean> {
    return new Promise((resolve, reject) => {
      if (value > 1) {
        reject(new Error("testing"));
      } else {
        resolve(true);
      }
    });
  }
}

HTML Code:

<h2>Example of Promise and Observable </h2>

<br/>
<button (click)="createPromise()">Create Promise</button>
<br/>
<br/>
<button (click)="createObservable()">Create Observable</button>
<br/>
<br/>
<button (click)="subscribeObservable()">Subscribe Observable</button>
<br/>
<br/>
<button (click)="createObservableNext()">Create Observable Next</button>
<br/>
<br/>
<button (click)="createToPromiseByObservable()">Create Promise by Observable</button>
<br/>

Which is easy to use between a promise or observable? So here is a simple answer to this question.

Promises are used in Angular to resolve asynchronous operations, and Observables are used when the data comes from an external source like an API.

Promises can be resolved with a single value or an array of values, and Observables emit one or more values over time.

So, while managing an HTTP search, Promise can only handle a single response for the same request; however, if there are numerous results to the same request, we must use Observable.

To check the live demonstration of the code, click here.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook

Related Article - Angular Promise

Related Article - Angular Observable