Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between observables and promises in JavaScript?

So i've read that observables are looking to overtake promises in terms of usage in some of upcoming JavaScript MVC's:

  • Angular 2.0
  • Falcor used by Netflix

What is the difference between observables and promises?

Updated: Apologies! removed my falsy statement.

like image 762
chrisjlee Avatar asked Mar 17 '16 15:03

chrisjlee


People also ask

Which is better observables or promises?

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 also has the advantage over Promise to be cancellable.

What are observables in JavaScript?

Observable JavaScript represents a progressive way of handling events, async the activity, and multiple values in JavaScript. These observables are just the functions that throw values and Objects known as observers subscribe to such values that define the callback functions such as error(), next() and complete().

What are promises in JavaScript?

A Promise is a JavaScript object that links producing code and consuming code.

What is difference between subscribe and observable?

Observables are not executed until a consumer subscribes. The subscribe() executes the defined behavior once, and it can be called again. Each subscription has its own computation. Resubscription causes recomputation of values.


2 Answers

What is the difference between observables and promises?

Simply put: A promise resolves to a single value asynchronously, an observable resolves to (or emits) multiple values asynchronously (over time).

Concrete examples:

  • Promise: Response from an Ajax call
  • Observable: Click events

More information can be found here: http://reactivex.io/intro.html

i've read that observables are looking to overtake promises

Unlikely. Observables might be the better solution to certain problems, but that doesn't make promises obsolete (if that's what you mean).

like image 173
Felix Kling Avatar answered Sep 27 '22 20:09

Felix Kling


Promises are a representation of 1 future value. Observables are a representation for a possibly infinite amount of values.

Promises will trigger the fetching of that value immediately upon creation. Observables will only start producing values when you subscribe to them. (Unless it's a hot observable, but that's outside the scope of this question)

Promises are designed to represent AJAX calls. Observables are designed to represent anything: events, data from databases, data from ajax calls, (possibly infinite) sequences, etc.

like image 36
Moeri Avatar answered Sep 27 '22 18:09

Moeri