Promise和Observable的区别

refer: promise-vs-observable
先上总结:

image.png

Promise

A Promise handles a single event when an async operation completes or fails.
Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.

Observable

An Observable is like a Stream and allows to pass zero or more events where the callback is called for each event.
Observable 允许 0 or more event,回调函数在每次event的时候都会被执行。

Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.
通常来说,Observable比Promise更好,因为它提供了不止Promise的其他特性。

Observable also has the advantage over Promise to be cancelable. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the Subscription of an Observable allows to cancel the subscription, while a Promise will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore.
Observable有一个优势:可取消。如果不再需要一个HTTP请求/某些昂贵的异步操作,Observable可以取消订阅,而Promise仍会执行 success/failed 回调函数。

Observable provides operators like map, forEach, reduce, ... similar to an array. There are also powerful operators like retry(), or replay(), ... that are often quite handy. A Promise handles a single event when an async operation completes or fails.
此外,Observable还提供了很多类数组的操作子,以及更多的高阶操作子。

Promise VS Observable

Both Promises and Observables will help us work with the asynchronous functionalities in JavaScript. They are very similar in many cases, however, there are still some differences between the two as well, promises are values that will resolve in asynchronous ways like http calls. On the other hand, observables deal with sequence of asynchronous events. The main differences are listed as below:

promise:

  • having one pipe line
  • usually only use with async data return
  • not easy to cancel

observable:

  • are cancellable
  • are retriable by nature such as retry and retryWhen
  • stream data in multiple pipe lines
  • having array-like operations like map, filter etc
  • can be created from other sources like events
  • they are function, which could be subscribed later on

Also, I've created the graphical image for you below to show the differences visually:

image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文转载自知乎 作者:季子乌 笔记版权归笔记作者所有 其中英文语句取自:英语流利说-懂你英语 ——————————...
    Danny_Edward阅读 43,950评论 4 38
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,928评论 0 0
  • 葵子姑娘一个人的故事 ……只有你自己一个人的故事。 葵子姑娘用淡定先生的名字写了一个只有葵子姑娘一个人的故事。 (...
    书中的美人鱼阅读 134评论 0 0
  • 今年的这个时候 阴雨连绵 不知道称之为哪个季节 好不容易等到了天空放晴 借着绵绵的光线 拍了几张照片 家里的绿植特...
    楠熙子阅读 204评论 0 1
  • 无论循环无数,总是莫名的从头再来,或许这就是一种感动,也或许是一种忧郁。多愁善感的眉头又悄然闪动,黑白间镶盼的眼神...
    文林cium阅读 129评论 0 3