Promises:

Use promises when we want a single async operation of which we want to execute the result.

In below example:

var promise = new Promise((resolve, reject) => {
  // do something once, possibly async
    if (/* if success*/) {
    resolve("condition works!");
  }
  else {
    reject(Error("condition fails"));
  }
});

//after the promise is resolved or rejected we can execute .then or .catch method on it

promise.then((val) => console.log(val))      // it will logs the resolve argument
       .catch((val) => console.log(val));    // it willlogs the reject argument

So a promise executes some code where it either resolves or rejects. If either resolve or reject is called the promise goes from a pending state to either a resolved or rejected state. When the promise state is resolved the then() method is called. When the promise state is rejected, the catch() method is called.

Observables:

In Observables when there is a stream (of data) over time which you need to be handled. A stream is a sequence of data elements which are being made available over time.

Examples of streams are:

  1. User events, e.g. click, or keydown, keyup events. The user generates events (data) over time.
  2. Web sockets, after the client makes a Web Socket connection to the server it pushes data over time.

In the Observable itself is specified when the next event happened, when an error occurs, or when the Observable is completed. Then we can subscribe to this observable, which activates it and in this subscription, we can pass in 3 callbacks (don’t always have to pass in all). One callback to be executed for success, one callback for error, and one callback for completion. For example:

const observable = Rx.Observable.create(observer => {
  // create a single value and complete
  observer.onNext(1);
  observer.onCompleted();
});

source.subscribe(
  x => console.log('onNext: %s', x),   //  success callback function
  e => console.log('onError: %s', e),  //  error callback function
  () => console.log('onCompleted')     //  completion callback function
 );
 

When we creating an observable it requires a callback functions which are supplies of observer as an argument.With this observer, we can call onNextonCompletedonError. Then when the Observable is subscribed to it will call the corresponding callbacks passed into the subscription.

By admin

Leave a Reply

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