RxJS: How to Use Lettable Operators with Promises

Image for post
Image for post
Photo by Gary Bendig on Unsplash

With the release of RxJS 5.5.0-beta.5, toPromise is now attached to Observable.prototype, rendering this look at its ‘lettable’ variant a historical curiosity.

Converting observables to promises is an antipattern. Unless you are integrating observables with a promise-based API, there is no reason to convert an observable into a promise.

If you are integrating with such an API, in his article RxJS Observable interop with Promises and Async-Await, Ben Lesh shows how it can be done. However, that article uses the prototype-patched toPromise method. Let’s have a look at the how the ‘lettable’ toPromise function — introduced in the RxJS 5.5.0 beta — could be used.

With toPromise, ‘lettable’ is something of a misnomer, as it cannot be used with the let operator. Lettable operators are higher-order functions that return functions that receive and return observables. The toPromise higher-order function returns a function that receives an observable, but it returns a promise — so it’s not lettable.

To convert an observable to a promise, toPromise needs to be called and the observable needs to be passed to the function it returns, like this:

The toPromise call cannot be placed within the call to pipe, as pipe will only accept functions that receive and return observables. Instead, it must be called separately.

Usually, toPromise would be called without an argument. However, if a particular promise implementation is to be used, a constructor can be passed. For example, a Bluebird promise could used, like this:

An any assertion is required because Bluebird does not have a Symbol.species property, making TypeScript deem it incompatible with typeof Promise.

If the TC39 pipeline operator proposal is eventually accepted into the ECMAScript standard, there will be an alternative, arguably-more-natural syntax, that looks like this:

This post is also published on my personal blog: ncjamieson.com.

RxJS core team member; front-end developer; mentor; speaker; open-source contributor

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store