When to use Promise over observable?

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

    An observable does everything that a promise does and more. It can always be switched to a promise with toPromise() method in case a promise is expected.

    An observable must be chosen over a promise if

    • any features that are intrinsic to observables and not promises and explained in detail in related question is in demand (notably unsubscription, incomplete observables and observables that receive multiple values)
    • API that consumes it expects an observable and doesn't use Observable.from(...) safety structure to unify observables and promises

    An observable may be chosen over a promise if the code where it's used uses observables exclusively.

    A promise must be chosen over an observable if API that consumes it expects a promise and doesn't use Observable.from(...) safety structure.

    A promise may be chosen over an observable if

    • the code where it's used uses promises exclusively (notably async functions)
    • it needs to be asynchronous by design
    • it needs to be immediately subscribed and chained then, because a chain should be broken in observables let observable = ...; observable.subscribe(...); return observable (this also requires multiple subscriptions to be tracked in case an observable is cancellable)

提交回复
热议问题