Open In App

What is the Difference Between Promises and Observables in Angular ?

Angular is a TypeScript-based Single-Page Application framework used to create dynamic and responsive web applications. It is one of the most popular and robust frameworks. One of its key features is to handle Asynchronous Operations effectively. In Asynchronous, code is not executed sequentially rather it follows multi-threading. When we make an HTTP request, the next code after that request need not wait for it to finish execution. The request can be running in the background simultaneously without blocking the remaining code. Some of the scenarios where we need Asynchronous Programming are when making HTTP requests to fetch data from the server, and real-time data streams where data need to be retrieved continuously like in the stock market, running concurrent applications, etc. This can be done in two ways i.e., Promise and Observable.

Promise

A Promise represents a single value in the future, that may not be available at present but is expected to be resolved or rejected in the future. It is more readable and maintainable in asynchronous. A Promise object has two possible states, i.e. the resolve and reject. It offers a structured way to handle resolved or rejected states. It has “then ()” to handle resolved states and “catch ()” to handle rejected ones. These help in making promises a suitable choice for single asynchronous operations. Suitable for activities such as reading data from server, files. There are 4 phases in it, namely, fulfilled, rejected, pending, and settled.



Syntax

const myPromise = new Promise((resolve, reject) => {

    // Asynchronous operation
    if (success) {
        resolve(response);
    } else {
        reject(error);
    }
});

myPromise.then(result => {

    // Handle success here
}).catch(error => {

    // Handle error here
});

Approach

In this approach, we will try to change the appeared data after some time without user intervention using promise. Here, we have an HTML code containing only data that is retrieved from a typescript file using String Interpolation. Now we have declared that data variable initially. Then using a Promise function, we have written a Promise which if in success changes the data variable to something else as below. So, as we have kept it as true, then the variable got changed below. This true and false may depend on various things in real-time projects. But for now, to demonstrate we keep it true and the time delay as 5 seconds.

Example: This example illustrates the basic usage of the Promise in Angular.






<!-- app.component.html -->
<div>
    <p>{{ data }}</p>
</div>




// app.component.ts
import { Component, OnInit } from '@angular/core';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    data: string = "data before promise response";
  
    ngOnInit() {
      
        // Asynchronous operation with a Promise
        this.fetchDataWithPromise()
            .then(data => {
                this.data = data;
            })
            .catch(error => {
                console.error(error);
            });
    }
  
    fetchDataWithPromise(): Promise<string> {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
              
                // Data retrieved after some delay
                const success = true;
                  
                 // You can change this to false to simulate an error
                if (success) {
                    resolve("Data fetched with a Promise"+
                            " and displayed after 5 seconds");
                } else {
                    reject("Error occurred while fetching data");
                }
            }, 5000);
        });
    }
}

Output: Here data string is changed after the promise is retrieved.

 

Disadvantages of Promises

Observable

An Observable is a powerful concept that is in Angular through the RxJS library. These are a sequence of values that can be arrived at over time. These can emit values either synchronously or asynchronously. Mainly used to handle streams of data that change over time. These can emit multiple values, unlike promises. These offer a great set of complex features such as cancellation, retrying, and debouncing. Suitable for real-time updates like stock market dashboards.

Syntax

import { Observable } from 'rxjs';

const myObservable = new Observable(observer => {

    // Asynchronous operation
    if (success) {
        observer.next(result);
    } else {
        observer.error(error);
    }
});

myObservable.subscribe(result => {

    // Handle success here
}, error => {

    // Handle error here
});

Example: This example describes the basic implementation of the Observable in Angular.




<!-- app.component.html -->
<div>
    <p>{{ data }}</p>
</div>




// app.component.ts
  
import { Component, OnInit } 
    from '@angular/core';
import { Observable } from 'rxjs';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    data: string = "data before observable response";
  
    ngOnInit() {
      
        // Simulate an asynchronous operation 
        // with an Observable
        this.fetchDataWithObservable().subscribe(
            data => {
                this.data = data;
            },
            error => {
                console.error(error);
            }
        );
    }
  
    fetchDataWithObservable(): Observable<string> {
        return new Observable(observer => {
            setTimeout(() => {
              
                // Data retrireving after some delay
                const success = true;
                  
                // You can change this to false 
                // to simulate an error
                if (success) {
                    observer.next("Data fetched with an Observable"
                                  " and displayed after 5 sec");
                    observer.complete();
                } else {
                    observer.error("Error occurred while fetching data");
                }
            }, 5000);
        });
    }
}

Output: Here is the output for the above example, with before and after observable responses.

 

Disadvantages of Observables

Difference between Promise and Observable

 

Promise

Observable

Handling multiple values Handles single value. Handle multiple values at a time.
Asynchronous support Suitable for asynchronous communication Suitable for both synchronous and asynchronous communication
Cancellation Cannot be canceled once initiated. Can be canceled whenever we want.
Complex data transformation Limited support. Wide range of support.
Error Handling The catch() method is used for handling errors. This offers different mechanisms.
Conciseness Simple and concise syntax. More complex due to extensive support.
Use Cases Suitable for one-time tasks like reading files. Suitable for continuous real-time updates like in stock market dashboards.

Article Tags :