Angular Promise vs Observable: Ultimate Differences You Must Know

JavaScript strictly follows the asynchronous concurrent language and its engine instantly moves to execute the next statement without waiting for the concurrent statement to finish.

Such a concept is called the asynchronous function, and you need to deal with the callbacks approach. So, I know it’s a challenging task to manage the codes, making the callback hell.

Angular Promises and Observables are the one-stop solutions to overcome such situations. Their implementations help us deal with that asynchronous code more cleanly. However, they have different APIs, and their motivation is slightly different.

And we have come up with an article that depicts the technical difference between Angular promise vs Observable.

What is Promise in Angular?

One of the best ways to execute asynchronous functions in your application that typically uses callbacks is opting for promise in Angular development.

The promise in Angular takes place while emitting and completing (resolving or rejecting) one value at a time. So if you’re using an Angular promise, it becomes easy for you to emit a single event from the API.

Then, the controller’s (directive) sole responsibility is to register up to three callbacks – success, error, and notifications.

Generally, four states of the Angular Promise are available for your Angular application development.

  • fulfilled
  • rejected
  • pending
  • settled

Remember that Angular Promise is not active as Observable. It means AngularJS developers are not allowed to cancel any specific event once it starts. So, passing the callback to the Promise constructor (controller or directive) will provide you with two options: either resolve or reject the function, depending on your needs.

Get Custom-Tailored Web App Development Solutions For Your Business Needs

We strictly adhere to the standard software development lifecycle to provide the best possible IT solutions for your business success.

What is an Observable in Angular?

Observables are preferable to Angular promise as they allow you to run functions asynchronously and synchronously. Furthermore, it means that you can deliver multiple values over time with the help of Observables.

Such values are actively responsible for handling 0, 1, or multiple events, and that too by using the same API for every event. The excellent part of Angular Observables is the number of operators actively simplifying coding, including retry(), replay(), map, forEach, reduce and others.

With the help of Observables, the first thing that you need to perform is to have a subscription to start emitting values. If you do not perform this step, it’s just a blueprint of code responsible for handling future emits.

Related Post: Resolver in Angular

Angular Promise vs Observable: Differences You Must Know

Now, it’s high time to see the technical differences between Angular Promise vs Observable. I have gathered the list of examples to clarify doubts about the difference between Angular Promise and Observables.

  1. Angular Promise handles one value; Observables handles multiple values.

    One of the significant differences between Observable vs Angular Promise is that you are now allowed to change the fulfilled value. So instead, you can just emit (either reject or resolver) a single value for your Angular application.

    To understand this concept, you need to have basic information of what is Angular.

    And if I talk about Observables, you can freely emit multiple results. The subscriber will receive results until the observer is completed or unsubscribed.

    Let’s see an example of handling values in terms of Angular Promise vs Observable.

    Copy
    // Promises
    const x = new Promise((resolve) => {
        setInterval(() => {
            // ✅ when resolve is called, the promise will become
            // fullfilled and it's value won't ever change
            resolve(Math.random() * 10)
        }, 3000);
    });
    
    // Observables
    const observable$ = rxjs.Observable.create((observer) => {
      // ✅ you can pass multiple values by using `next` method
      observer.next(1);
      observer.next(2);
      observer.next(3);
      observer.complete();
    })
    
    // ✅ base will be receiving values untils it's completed
    observable$
        .subscribe(
          v => console.log(v),
          err => console.log(err),
          done => console.log("completed")
        );

    Observables are responsive tools that quickly listen to data streams. In addition, there exists a bidirectional kind of Observable: Subjects, and they are a perfect use case for those web sockets. The RxJS library helps you to deal with shipping with a thin wrapper on web sockets.

    import { webSocket } from “rxjs/webSocket”;

    We crafted web and mobile application that allows users to easily search for a car by entering the essential car options, colour specifications, and location.

  2. Observable subscriptions are cancellable; promises aren’t

    Once an Angular promise is started, it seems impossible to cancel the event. So instead, the callback passed to the Promise constructor is solely responsible for resolving or rejecting the promise.

    The subscriber reacts to the result once fired; hence, it’s completely passive.

    Compared to Angular Promise, Observables are less passive and on subscribe creation process, you can quickly opt out of the observer at any time.

    So, if you are no longer interested in getting the response, you can opt for such scenarios. The best example is when a user leaves a page.

    Yes, you’ll find multiple ways to cancel/complete subscribers.

    Some of the common one to cancel subscribers are mentioned below:

    • unsubscribe: It allows you to cancel the subscription from the Observation manually.
    • take: It enables you to take number X of elements and easily cancel the subscription process.
    • takeUntil: It makes it easy for you to take values until the passed Observable emits any value.

    Let’s go through an example to demonstrate it.

    Copy
    // ✅ 1. Cancelling by using the unsubscribe method
    const observable1$ = rxjs.interval(1000);
    const subscription1$ = observable1$
      .subscribe(x => console.log(x));
    
    subscription1$.unsubscribe();
    
    // ✅ 2. Cancelling by taking a number of elements
    const observable2$ = rxjs.interval(1000);
    
    observable2$
      .pipe(rxjs.operators.take(5))
      .subscribe(x => console.log(x));
    
    // ✅ 3. Conditionally stop listineing for more elements
    const subject3$ = new rxjs.Subject();
    const observable3$ = rxjs.interval(1000);
    
    observable3$
      .pipe(rxjs.operators.takeUntil(subject3$))
      .subscribe(x => {
        console.log(x);
        if (Math.random() > 0.5) {
          subject3$.next(1);
          subject3$.complete();
          console.log('complete');
        }
      });

    The operators of Observable are essential as it allows you to compose declaratively complex asynchronous operations quickly.

    Planning To Develop a Robust Single-Page Application?

    Our Angular development team has core expertise in designing and building feature-rich applications for all your business needs.

  3. Eager vs lazy execution

    In the discussion about Angular Promise vs Observable, we need to understand the process of execution. And that is done by using the Eager and Lazy execution method.

    Let’s put it simply. You can execute the Angular Promises eagerly. On the other hand, Observables are executed lazily.

    What is Lazy and Eager execution?

    • Eager: It allows you to execute the Promise callback, especially at the constructor level.
    • Lazy: The Producer function will only trigger after a subscription is created for that Observable. Otherwise, it will stay idle.

    I’ll make it easier for you by demonstrating it with a good example.

    Copy
    const foo = new Promise((resolve) => {
      console.log('1. Callback execution');
      resolve(true);
    });
    
    foo.then(() => {
      console.log('2. Promise resolution');
    });
    
    console.log('3. Pre exit method statement');
    
    // ✅ console output
    // 1. Callback execution
    // 3. Pre exit method statement
    // 2. Promise resolution
    
    const observable$ = new rxjs.Observable(observer => {
      console.log('1. Execution of observable body');
      observer.next(1);
      observer.complete();
    });
    
    console.log('2. Pre Subscribe statement');
    
    observable$.subscribe(() => {
      console.log('3. Execution of subscribe callback')
    });
    
    // ✅ console output
    // 2. Pre Subscribe statement
    // 1. Execution of observable body
    // 3. Execution of subscribe callback

    The above example depicts the sequence that typically occurs: 1. Callback execution and 1. Execution of observable body.

  4. Runtime execution

    Once ES Promises enters the resolved state, it becomes pretty easy for you to queue the callback in the microtask queue. Simply put, the execution takes place after the current macro task has been completed.

    Let’s see an example:

    Copy
    console.log('1. Start');
    
    setTimeout(() => {
        console.log('2. Timeout callback')
    }, 0);
    
    Promise.resolve().then(() => {
        console.log('3. Promise callback')
    });
    
    console.log('4. End');
    
    // ✅ outputs
    // 1. Start
    // 4. End
    // 3. Promise callback
    // 2. Timeout callback

    You can’t change the above behavior.

    Related Post: Angular Ivy

    Observables enable you to effortlessly fine-tune the runtime execution by strictly using schedulers. The primary role of a scheduler is to control the state, especially when a subscription starts and you receive notifications for the same.

    • null: You’ll receive notifications synchronously and recursively by default.
    • queueScheduler: It allows you to schedule quickly on a queue in the current event frame.
    • asapScheduler: You can efficiently schedule it on the microtask queue. And also, it uses the same queue as promises use.
    • asyncScheduler: This concept is just the same as scheduling a task using setInterval. So, you need to schedule it in the macro task queue.
    • animationFrameScheduler: relies on requestAnimationFrame API.

    I’ll demonstrate an example by using asapScheduler:

    Copy
    const observable1$ = rxjs.interval(1000)
      // ✅ using the asapScheduler scheduler
      .pipe(rxjs.operators.observeOn(rxjs.asapScheduler));
    
    const subscription1$ = observable1$
      .subscribe(x => console.log(x));
    
  5. Interoperability

    So, we have seen a lot of differences between Angular Promise and Observables. But the biggest question here is whether we can use both together. Or do we have to select only one of them?

    Well, the answer is No.

    • Observables can easily created from Promise, and you can efficiently drop Observable into a Promise.
    • Promises take only one value; you have to choose if you want the first or last value to be dumped on the Promise.
    • And if I talk about the rxjs library, it provides you with the firstValueFrom and lastValueFrom for that particular use case.

Let me demonstrate you with a simple example.

Copy
// ✅ Observable -> Promise
const source$ = rxjs.interval(2000).pipe(rxjs.operators.take(10));
// toPromise is deprecated in favor of firstValueFrom and lastValueFrom
// outputs 9
const result = await source$.toPromise();

// ✅ Promise -> Observable
const promise = Promise.resolve(10);
rxjs.from(promise)
  // outputs 10
  .subscribe(item => console.log(item));

Conclusion

I hope you clearly understand the technical difference between Angular Promise and Observable. It entirely depends on your business use case on when to use one or the other.

But they are going to play a vast role in solving the async paradigm in JavaScript. Moreover, observables are cost-effective as the Browser does not natively support them.

If you’re planning to develop a robust web application using the Angular framework, we are a renowned AngularJS development company. We have a team of Angular developers who are proficient in providing the best possible web app solutions for your business needs.

What is Promise in Angular Development?

JavaScript is a programming language created to add interactivity to web pages. However, in JavaScript coding, the developers find it quite challenging to deal with the callback functions. The reason is that they must deal with asynchronous events when users interact with a web page.

Such callback functions became a pain for many developers, especially when building complex and rich apps with JavaScript for modern browsers. To overcome such complexity, ES6 introduced Promises, a modern and powerful abstraction for writing asynchronous code in a better and easily maintainable way.

In this article, you’ll learn about what is Promise in Angular application and will come across the concept of JavaScript Promises introduced in ES6.

What is Promise in JavaScript?

A promise is a JavaScript or TypeScript object that may produce a value at some point in time. A promise may be in one of 4 possible states:

  • fulfilled – The action relating to the promise succeeded
  • rejected – The action relating to the promise failed just because an error occurs during promise implementation
  • pending – It’s an initial state that hasn’t fulfilled or rejected yet
  • settled – Has fulfilled or rejected

Get Custom-Tailored Web App Development Solutions For Your Business Needs

We strictly adhere to the standard software development lifecycle to provide the best possible IT solutions for your business success.

How To Create a Promise in JavaScript?

Let’s highlight a simple example of creating a promise in plain JavaScript.

Copy
var promise = new Promise((resolve, reject) => {
  resolve("Promise Resolved"); 
})

promise.then((success) => { 
  console.log(success);
})
.catch(function(error) => {
  console.log(error);
}); 
// Output: Promise Resolved

The developers from the leading AngularJS development company implements Promises by calling the then() and catch() methods.

  • then() method: It takes two callback functions as parameters and is invoked when a promise is either resolved or rejected.
  • catch() method: It takes one callback function and is invoked when an error occurs.

Now, let us understand the basic concept of “what is Promise in Angular?”

Related Post: Angular Resolver

What is Promise in Angular?

When the AngularJS developers are dealing with asynchronous operations like an HTTP request, they are not sure of the exact time to get a response from the server. By default, Javascript is a programming language that is

  • Synchronous;
  • Blocking; and
  • Single-threaded language.

In simple words, we can say that the Javascript engine can process only one code at a time in a single thread. So, when a thread is blocked, we can’t execute other code that is also blocked, making JS slow and unable to perform multiple operations.

On the other hand, the asynchronous operation is solely responsible for making code nonblocking. It means that it allows the developers to execute multiple codes at the same time.
In the Angular framework, the developers can quickly achieve asynchronous by utilising the following method.

  • The Callback function
  • The Promise from Javascript can be used in Angular.
  • Observable using Rxjs library in Angular: Library for reactive programming using Observables.

You may also like to read: What is Angular?

Moreover, while dealing with an asynchronous operation, the developers can quickly move the code to the following line by allowing UI remains responsive. The user continues working on the application while asynchronous operations like HTTP requests are processed in the background.

Now the concept of Promise in Angular comes into the picture. The Promise in Javascript is nothing but a piece of task that is wrapped in asynchronous operation and notified whenever the asynchronous process is completed or failed at some point in the future.

Two possible outcomes occur when the developer runs the Promise: The Promise is completed or failed. With the help of the async and await keyword with Promise, it becomes easy for the developers to deal with easy to read, write, and we can also use “try and catch” for error handling with (async & await).

Planning To Develop a Robust Single-Page Application?

Albiorix is a leading AngularJS Development Company having core expertise in designing and building feature-rich applications for all your business needs.

Angular Promise Example

Its time to see how to use promises in Angular development First, we will create a simple Angular application using Angular CLI.

ng new angular-promise-example –routing=false –style=css

This command will create a new Angular application with no routing and CSS for stylesheet format. Next, we will set up HttpClient to send API requests to web servers to create or fetch data.

Fetching data is a standard asynchronous operation as you always have to wait for an amount of time to receive the requested data. In Angular development, you can use HttpClient for fetching data.

HttpClient uses RxJS Observables to handle asynchronous operations; let’s see how to use JavaScript/ES6 Promises instead.

In the app/app.module.ts file of your project, add the following changes:

Copy
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule }  from '@angular/common/http';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, HttpClientModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Next, open the src/app/app.component.ts file and add the following code to send a HTTP GET request and process the response using a Promise in Angular.

Copy
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "Angular Application and Promises Example";API_KEY = "e40d07f00b094602953cc3bf8537477e";

constructor(private httpClient: HttpClient) {}

ngOnInit() {
console.log("Angular Promises");
this.fetchDataAsPromise()
.then((data) => {
console.log(JSON.stringify(data));
})
.catch((error) => {
console.log("Promise rejected with " + JSON.stringify(error));
});
}

fetchDataAsPromise() {
return this.httpClient
.get(
`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${this.API_KEY}`
)
.toPromise();
}
}

We import HttpClient and inject it via the component constructor and use it to send the HTTP request.

Next, we call the get() method to send the request and the toPromise() method to convert the returned RxJS Observable to a promise.

Copy
fetchDataAsPromise() {
return this.httpClient
.get(
`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${this.API_KEY}`
)
.toPromise();
}

In the ngOnInit() life-cycle method, we send the actual request by calling the then() method of the promise as follows:

Copy
this.fetchDataAsPromise()
.then((data) => {
console.log(JSON.stringify(data));
})
.catch((error) => {
console.log("Promise rejected with " + JSON.stringify(error));
});

If the promise is resolved successfully we simply output the data in the console and in case of an error we display the error.

Related Post: Angular Promise Vs Observable

Conclusion

So, I hope you got a clear vision on what is Promise in Angular development is. In addition, we came across the concept of JavaScript Promises introduced in ES6. We have seen the implementation of JavaScript promises that can be specifically included in the application.

In addition, we came across the example of creating a promise in the Angular application. Still, if you have any query related to web application development, Angular is the best and leading option that help you build applications for all business verticals.