• Angular
  • React
  • NextJs
  • Sass

Angular Observable vs Promise

By Webrecto, September 15, 2023

In this article, We will discuss about promise and observable. The promise and observable are two ways through which we can perform asynchronous operations in angular.

The promises and observable are one of the most important concepts of data management in angular applications. When we handle an asynchronous operation in angular, then we can do it with the help of promises and observables.

Angular Observable vs Promise

Observables in Angular

An observable is a function, this is introduced by RxJS. The observable handles a variety of common asynchronous operations over a period of time. The observable can emit multiple streams of values over a period of time. It can handle both synchronous and asynchronous operations in Angular.

Observable Syntax

const dataObservable = new Observable((data) => {
    data.next();
}).subscribe();
   

The observable function accepts a single parameter which is data. To read observable data, we use the subscribe method. The subscribe method plays a key role in executing code, the user can not read directly observable data without the subscribe method.

In the application, If an error occurs during code execution, the subscriber automatically unsubscribes from the observable.

dataObservable.unsubscribe();

Observables can have chaining and subscriptions. For example: forEach, filter, reduce etc, the operators can be used with observables.

Using Observable to pass values

const dataObservable = new Observable((data) => {
    data.next(5);
    data.next(15);
    data.next(20);
    data.next("Hello....");
}).subscribe(response => console.log("Response from Observable data:" + response));

Result:

Output will show in browser console


Response from Observable data: 5
Response from Observable data: 15
Response from Observable data: 20
Response from Observable data: Hello....


In the above example, I am creating a new Observable and in his passing the parameter. The data calls the next() inbuilt JavaScript method with the different values. After that, I subscribe to observable data with the .subscribe method. For the display data, I am using console.log in code. When the code is executed we can see the output in the browser console.

Promise in Angular

ThePromises simplify asynchronous code and it helps us work with asynchronous functionality in JavaScript. The promises handle one asynchronous operation over a period of time. A promise can emit only a single value at a time and execute instantly on creation. In promises operation, It does not provide an unsubscribe facility.

const dataPromise = new Promise((resolve, reject)=>{
   // logic code
});

There are four states of the Angular Promise

fulfilled - Action is fulfilled

rejected - Action failed

pending - Action has not succeeded or failed yet

settled - action is either fulfilled or rejected

A Promise is an object representing the final completion or failure of an asynchronous operation. The promise support only .then function and It does not handle the error itself, it always pushes the error to the child's promises.

Using Promise to pass values

const dataPromise = new Promise((data) => {
    data(5);
    data(15);
    data(25);
}).then(response => console.log('Response from Promise : ' + response));

Result

Response from Promise: 5

In the above code, I have created new Promise in which passed an data parameter, and it is invoking data() by input value, i.e. 5, 15, 25. Now once its executed, console.log statement is printed one responce from Promise.

Difference Between Promises and Observables

Observable Promise
Observable can emit multiple values. A promise can emit only a single value at a time.
Observables are lazy when we subscribe then only that will execute. Promises are not lazy; they will execute immediately on creation.
Observables are themselves responsible for handling errors. Promises always push the error to the child promises.
Observables can be cancelled whenever you need to stop listening from the receiving the values. Promises can never be cancelled and will always be executed.
Provide the map for forEach, filter, reduce, retry, and retryWhen operators. Promises do not provide any operations.
Observable less passive Promise is more passive compared to the Observable
It can be either Sync or Async. It is always Async, Once the value is resolved / rejected.
Observables are multicast, which means every time we subscribe to the observable. Promises are unicast, which means promises will be executed only once.

Complete Example

1: In this example, Observable will emit multiple values and Promise will emit only a single value.

Emit multiple values / Emit single values

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 {
  ngOnInit() {
    //Observable will emmit multiple values
    console.log("Observable will emmit multiple values - ");
        var observable = new Observable(res => {
        res.next("Hello Ramesh");
        res.next("Hello Santosh");
        res.next("Hello Akhilesh");
    });
    observable.subscribe(console.log)

   //Promise will emit only single values
    console.log("Promise will emit only single values - ");
    var promise = new Promise(res => {
        res("Hello Ramesh");
        res("Hello Santosh");
        res("Hello Akhilesh");
    });
    promise.then(console.log)
  }	
}

Output

You can see output in browser console.

Observable will emmit multiple values -
Hello Ramesh
Hello Santosh
Hello Akhilesh

Promise will emit only a single value -
Hello Ramesh

Synchronous/Asynchronous Observable Vs. Asynchronous Promise

2: In this example, Observable will perform synchronous and asynchronous behavior and Promise will perform only asynchronous behavior.

Observable will perform asynchronous and synchronous

   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 {
  ngOnInit() {
   //Asynchronous Observable example
    var observable = new Observable(res => {
      console.log("Name print start code...");
      setTimeout(() => {
        res.next("Hello Ramesh");
        res.next("Hello Santosh");
      }), 1000
      console.log("Name print end code...");
    });
    observable.subscribe(console.log)

    //Synchronous Observable example
    var observable = new Observable(res => {
      console.log("Name print start code...");
      res.next("Hello Ramesh");
      res.next("Hello Santosh");
      console.log("Name print end code...");
    });
    observable.subscribe(console.log)
 }	
}

Output

Asynchronous Observable example
Name print start code...
Name print end code...
Hello Ramesh
Hello Santosh

Synchronous Observable example
Name print start code...
Hello Ramesh
Hello Santosh
Name print end code...

3: In this example, Promise will perform only asynchronous behavior.

Promise perform asynchronous behavior

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 {
  ngOnInit() {
    // Asynchronous Promise example
    var promise = new Promise(res => {
        console.log("Name print start code...");
        res("Hello Ramesh");
        console.log("Name print end code...");
    });
    promise.then(console.log)
 }	
}

Output

Asynchronous Promise example
Name print start code...
Name print end code...
Hello Ramesh

Reference