When to use Promise over observable?

前端 未结 5 1698
梦毁少年i
梦毁少年i 2021-02-13 04:56

Is there any case, where Promise is more powerful as compare to observable? I know a lot of benefits of observables over promises. But Is there any case, I should use only promi

5条回答
  •  天涯浪人
    2021-02-13 05:11

    From: Randall Koutnik book “Build Reactive Websites with RxJS.” :

    Observables are like arrays in that they represent a collection of events, but are also like promises in that they’re asynchronous: each event in the collection arrives at some indeterminate point in the future. This is distinct from a collection of promises (like Promise.all) in that an observable can handle an arbitrary number of events, and a promise can only track one thing. An observable can be used to model clicks of a button. It represents all the clicks that will happen over the lifetime of the application, but the clicks will happen at some point in the future that we can’t predict.

    From: Anton Moiseev Book “Angular Development with Typescript, Second Edition.” :

    Promise has the following shortcomings:

    There’s no way to cancel a pending request made with a promise.

    When a promise resolves or rejects, the client receives either data or an error message, but in both cases it’ll be a single piece of data. A JavaScript promise doesn’t offer a way to handle a continuous stream of data chunks delivered over time.

    Observables don’t have these shortcomings.

提交回复
热议问题