What is the difference between Promises and Observables?

后端 未结 30 2611
小鲜肉
小鲜肉 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:25

    Observables and Promises are helping us to work with the asynchronous functionalities in JavaScript/typescript. They are very similar in many cases, however, there are still some differences between them.

    0 讨论(0)
  • 2020-11-22 00:26

    There is one downside of Observables missing in the answers. Promises allow to use the ES7 async/await functions. With them you can write asynchronous code like it would be a synchronous function call, so you don't need callbacks anymore. The only possibility for Observables to do this, is to convert them to Promises. But when you convert them to Promises, you can only have one return value again:

    async function getData(){
        const data = await observable.first().toPromise();
        //do stuff with 'data' (no callback function needed)
    }
    

    Further reading: How can I `await` on an Rx Observable?

    0 讨论(0)
  • 2020-11-22 00:30

    A Promise emits a single event when an async activity finishes or fails.

    An Observable is like a Stream (in many languages) and permits to pass at least zero or more events where the callback is required for every event.

    Frequently Observable is preferred over Promise since it gives the highlights of Promise and more. With Observable it doesn't matter if you need to handle 0, 1, or various events. You can use the similar API for each case.

    Promise: promise emits a single value

    For example:

    const numberPromise = new Promise((resolve) => {
        resolve(5);
        resolve(10);
    });
    
    numberPromise.then(value => console.log(value));
    // still prints only 5
    

    Observable: Emits multiple values over a period of time

    For example:

      const numberObservable = new Observable((observer) => {
            observer.next(5);
            observer.next(10);
        });
    
    numberObservable.subscribe(value => console.log(value));
    // prints 5 and 10
    

    we can think of an observable like a stream which emits multiple values over a period of time and the same callback function is called for each item emitted so with an observable we can use the same API to handled asynchronous data. whether that data is transmitted as a single value or multiple values over some stretch of time.

    Promise:

    • A promise is Not Lazy
    • A Promise cannot be cancelled

    Observable:

    • Observable is Lazy. The "Observable" is slow. It isn't called until we are subscribed to it.
    • An Observable can be cancelled by using the unsubscribe() method
    • An addition Observable provides many powerful operators like map, foreach, filter, reduce, retry, retryWhen etc.

    Angular Promises vs Observables

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 00:31

    Promises and Observables both handle the asynchronous call only.

    Here are the differences between them:

    Observable

    1. Emits multiple values over a period of time
    2. Is not called until we subscribe to the Observable
    3. Can be canceled by using the unsubscribe() method
    4. Provides the map, forEach, filter, reduce, retry, and retryWhen operators

    Promise

    1. Emits only a single value at a time

    2. Calls the services without .then and .catch

    3. Cannot be canceled

    4. Does not provide any operators

    0 讨论(0)
  • 2020-11-22 00:31

    Promise emits a single value while Observable emits multiple values. So, while handling a HTTP request, Promise can manage a single response for the same request, but what if there are multiple responses to the same request, then we have to use Observable. Yes, Observable can handle multiple responses for the same request.

    Promise

    const promise = new Promise((data) =>
    { data(1);
      data(2);
      data(3); })
    .then(element => console.log(‘Promise ‘ + element));
    

    Output

    Promise 1
    

    Observable

    const observable = new Observable((data) => {
    data.next(1);
    data.next(2);
    data.next(3);
    }).subscribe(element => console.log('Observable ' + element));
    

    Output

    Observable 1
    Observable 2
    Observable 3
    
    0 讨论(0)
提交回复
热议问题