Promises

vs

Observables

  • Callbacks
  • Generators
  • Async / await
  • Promises
  • Observables
getLoggedInUser((err, user) => {
  if (err) {
    displayError();
    return;
  }
  getMoviesForUser(user, (err, userMovies) => {
    if (err) {
      displayError();
      return;
    }
    getMovieDetails(userMovies[0], (err, movieDetails) => {
      if (err) {
        displayError();
        return;
      }
      displayMovie(movieDetails);
    });
  });
});

Callbacks

Promises

Value

function createUser(user) {
  return new Promise((resolve, reject) => {
    doCreateUser(user, (err, result) => {
      if(err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
}
createUser(user)
  .then(result => display(result))
  .catch(err => displayError());
function doSomething(user) {
  return new Promise((resolve, reject) => {
    console.log(`I'm doing some stuff...`);
  });
}

doSomething();
function doSomething() {
  return new Promise((resolve, reject) => {
    resolve(1);
    resolve(2);
    reject(3);
  });
}

doSomething().then(onSuccess, onFailure);
  • Are part of EcmaScript specification
  • Can only be resolved once
  • Are not guaranteed to be resolved
  • Are not lazy
  • Cannot be cancelled

Promises

Observables

RxJS

RxJS

import { Observable } from 'rxjs';

const hello = Observable.create(function(observer) {
  observer.next('Hello');
  observer.next('World');
  observer.complete();
});

hello.subscribe(val => console.log(val));
const observable = getRealTimeData();

Hot'n'Cold

const source = new Observable((observer) => {
  const socket = new WebSocket('ws://my-url');
  socket.addEventListener('message', (event) => {
    observer.next(event);
  });
  return () => socket.close();
});

(not the Katy Perry song...)

const socket = new WebSocket('ws://my-url');
const source = new Observable((observer) => {
  socket.addEventListener('message', (event) => {
    observer.next(event);
  });
});
import { Observable } from 'rxjs';

const subscription = getData().subscribe(data => console.log(data));

subscription.unsubscribe();
  • Are not part of EcmaScript specification
  • Can have multiple values
  • Are not guaranteed to be resolved
  • Can be lazy (hot vs cold)
  • Can be cancelled

Observables

Promises
vs
Observables

  • You have only one event
  • Work must be done only once
  • Your data could change over time
  • You will receive several events
  • You have complex operations
  • You may need to cancel the operation

Thank you!

Promises vs Observables

By ereold

Promises vs Observables

  • 1,012