When to use Promises and Observables in Angular

16 / Apr / 2024 by Guddu Kumar 0 comments

One of the most confusing scenarios is whether I should use a promise or an observable.

 

Have you ever worked with both Promises and Observable? Or maybe you’ve heard of them but don’t know which one to use at what time? To avoid this confusion, we need to understand their differences to pick the right one for our needs. It really depends on your application and which one to use.

Observables and promises both assist us in working with asynchronous functionality in JavaScript (angular).

Let’s start our discussion on:

Promises:

  • It can emit a single value at a time.
  • We can’t cancel the promises.
  • Are not lazy: execute immediately after creation.
  • It doesn’t support operators like map, filter, reduce, retry, retryWhen, and so many other RxJS operators.

Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn’t so far.

Checkout some examples

Emitting value: 

        var promise = new Promise(res => {
              res("Hello To");
              res("Hello The");
              res("Hello New");
          });
          promise.then(console.log);
        //output
       //Hello To --> Promise will emit only single values that's why other two values are not emmited.

Lazy Loading: 

        var promise = new Promise(res => {
              console.log('Promise start executing...');
                 //In console can see this output before calling promise it will initialized on creation and eagerly load.
              res('Hello....');
            });
            //Call promise
            promise.then(console.log);
            //Output
            //Promise start executing...
            //Hello....
     
Asynchronous Promise: 
var promise = new Promise(res => {
              console.log('Start Executing...');
              res('Hello...');
              console.log('Execution End...');
            });
            promise.then(console.log);
            //Output
            //Start Executing...
            //Execution End...
            //Hello...

  Observable:

  • Observables can emit multiple values asynchronously as a stream of data.
  • We can cancel the observable at any time.
  • Are lazy: they’re not executed until we subscribe to them using the subscribe() method.
  • It support operators like map, filter, reduce, retry, retryWhen, and so many other RxJS operators.

   Checkout some examples:

Emitting value:

          var observable = new Observable(res => {
            res.next('Hello To');
            res.next('Hello The');
            res.next('Hello New');
          });
          observable.subscribe(console.log);
          //Output --> Observable can emmit multiple values
          //Hello To
          //Hello The
          //Hello New

Lazy Loading:

         var observable = new Observable(res => {
              console.log("Observable start executing..."); // this line will not print untill subscribed
              res.next('Hello....');
            });
            observable.subscribe(console.log); //Whenever subscribe observable then only it will emmit values beacuse it is lazy load.
            //Output
            //Observable start executing...
            //Hello....
   
  Asynchronous/synchronous observable:
                 //Async Observable
 var observable = new Observable(res => {
                console.log('Start Executing...');
                setTimeout(() => {
                  res.next('Hello To');
                  res.next('Hello The');
                  res.next('Hello New');
                }),
                  1000;

                console.log('Execution End...');
              });
              observable.subscribe(console.log);
            
               //Output
              //Start Executing...
              //Execution End...
              //Hello To
              //Hello The
              //Hello New


              //Sync Observable
              var observable = new Observable(res => {
                console.log('Start Executing...');
                res.next('Hello To');
                res.next('Hello The');
                res.next('Hello New');
                console.log('Execution End...');
              });
              observable.subscribe(console.log);
             
              //Output
              //Start Executing...
             //Hello To
              //Hello The
              //Hello New
              //Execution End...

Conclusion:

Observables and Promises are fundamental components of contemporary RxJS and JavaScript applications. While Observables excel at managing numerous asynchronous events over time, Promises are best suited for handling solitary asynchronous tasks. Both are effective technologies for facilitating real-time communication between various application components. Comprehending these ideas enables developers to select the appropriate tool for different asynchronous programming situations, improving the effectiveness and responsiveness of their apps.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *