Skip to content

Instantly share code, notes, and snippets.

@rpominov
Last active June 11, 2016 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpominov/15414fdb166887fcac1b to your computer and use it in GitHub Desktop.
Save rpominov/15414fdb166887fcac1b to your computer and use it in GitHub Desktop.
Promises how I would do them

Promises how I would do them

1. No over polymorphic .then

Four methods instead: .map(a -> b), .mapError(a -> b), .flatMap(a -> Promise), .flatMapError(a -> Promise).

Why?

2. Ability to unsubscribe (cancelation)

The four methods above should not activate the promise, instead we should have additional method to subscribe:

let p = Promise((resolve, reject) => {
  // we get here when the promise gets a first subscriber (i.e. activates)
  return () => {
    // we get here when/if the promise loses all subscribers
  };
});

let unsubscribe = p.map(foo).flatMap(bar).subscribe(onSuccess, onFail);

// maybe later ...
unsubscribe();

Why?

See "RxJS Observables vs Promises", and a practical example of this feature being used in ajax() function from this demo http://jsfiddle.net/fwo0toLx/6/

3. No exceptions catching

Make it up to the developer. If it needed (which is very rare), one can do it manually:

foo.flatMap(x => {
  try {
    return Promise.resolved(fnThatMightThrow(x));
  } catch (e) {
    return Promise.rejected(e);
  }
});

Why?

Actually, not 100% sure about this one :)

@rpominov
Copy link
Author

https://github.com/folktale/data.task — this is very close. A bit different approach for unsubscribing / cleanup, but 100% match in everything else (up to methods' names).

@rpominov
Copy link
Author

Should probably split "Ability to unsubscribe" into "Cancelation" & "Lazy execution"...

@rpominov
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment