When to use Promise over observable?

前端 未结 5 1699
梦毁少年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:18

    Use Promise instead of an Observable, when:

    • You need to handle the (future response) event no matter what (no unsubscribe, no cancel: after you subscribe, there will be an answer, 100%, and you will have to handle it, 100%, the code will get executed)
    • One Subscription = One Event handling: there will be only one event from the source, so the future response and the completition is the same event.

    Use Observable instead of a Promise, when:

    • You want to have the ability to accept multiple events from the same source
    • You need a "I am finished with this event stream" handler
    • You want to be able to unsubscribe from a possibly never ending stream of data, and re-subscribe anytime (meaning also that you might don't really need to fulfill the subscription at all: for instance, if nothing happens in 10 sec, let's unsubscribe, nobody will ever handle the late answer)
    • You want to use the RxJS "Stream API" to preprocess the data of your responses.

    Generally, the Observable pattern is an extended Promise pattern, with a lot more tools and functionality. It is up to you to decide to limit the code with Promises or not. It was first a custom libary, then got included in ES2016.

    Also, I suggest researching the issue with specific problem parameters: you need the app to be faster? You will use legacy modules?

提交回复
热议问题