Understanding the toPromise() Deprecation

Learn about the deprecation of the toPromise() method and the functions that replace it.

One of the major deprecations of RxJS 7 is toPromise(), which will be deleted permanently after the release of RxJS 8. So it’s highly recommended that we avoid using toPromise() in future development.

Now let’s give a little bit of background to understand the reason behind this deprecation. It’s important to understand the use case of toPromise(), why this particular method is available, and when to use it. Additionally, it’s important to understand the incoherent behavior of this method in RxJS 6 in order to anticipate problems that might arise.

What is a promise?

Promises are used by many developers nowadays, and there are thousands of promise-based libraries. A promise is an object that holds the result (or failure) of an asynchronous operation.

Promises have been available in JavaScript through third-party libraries such as jQuery. Additionally, ECMAScript 6 added built-in support to JavaScript for promises.

The common key point between observables and promises is that both objects could produce values over time. However, the major difference is that observables can produce no value or more than one, while promises only produce one value when resolved successfully.

The toPromise() method available in RxJS is a utility method that is used to convert an observable to a promise. The toPromise() subscribes to the observable and returns the last value emitted by this observable.

In RxJS 6, when an error happens, toPromise() returns undefined. But this is not accurate!

That’s because we cannot differentiate between the case where no value was emitted before the completion of the observable and the case where an undefined value was emitted last.

Examples

Let’s look at the first example in the following snippet. Here, toPromise() will return the last value emitted by the observable, which is “World”:

Get hands-on with 1200+ tech skills courses.