What is the difference between Promises and Observables?

后端 未结 30 2755
小鲜肉
小鲜肉 2020-11-21 23:48

What is the difference between Promise and Observable in Angular?

An example on each would be helpful in understanding both the cases. In w

30条回答
  •  情歌与酒
    2020-11-22 00:30

    Promise:

    An Async Event Handler - The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

    Syntax: new Promise(executor);

    Eg:

    var promise_eg = new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve('foo');
      }, 300);
    });
    
    promise_eg.then(function(value) {
      console.log(value);
      // expected output: "foo"
    });
    
    console.log(promise_eg);
    

    About Promise: It has one pipeline so, it will return values only once when its called. its one way handler so once called you may not able to cancel. useful syntax you can play around, when() and then()

    Observables:

    Observables are lazy collections of multiple values over time. its really a great approach for async operations. it can be done with rxjs which has cross platform support can use with angular/react etc.

    its act like stream liner. can be multi pipeline. so once defined you can subscribe to get return results in many places.

    Syntax: import * as Rx from "@reactivex/rxjs"; to init:

    Rx.Observable.fromEvent(button, "click"),
    Rx.Subject()
    

    etc

    to subscribe: RxLogger.getInstance();

    Eg:

    import { range } from 'rxjs';
    import { map, filter } from 'rxjs/operators';
    
    range(1, 200).pipe(
      filter(x => x % 2 === 1),
      map(x => x + x)
    ).subscribe(x => console.log(x));
    

    since it support multi pipeline you can subscribe result in different location, it has much possibilities than promises.

    Usage: it has more possibilities like map, filter, pipe, map, concatMap etc

提交回复
热议问题