
RxJS operator ‘toPromise’
waits for your observable to complete!
Did you know that? I didn’t!
It turns out that the observable operator toPromise
waits for the observable to complete (or error) before actually resolving itself.
This came as a surprise to me, mainly because I haven’t really used the toPromise
operator all that much. I kinda expected the first emitted value to be used to resolve the promise. Or reject it.
These are the facts:
If you don’t trust me, as well you shouldn’t go to Stackblitz below
When the observable errors then the promise rejects.
It kind of makes sense when you think about it, right. Turning an observable into a promise i.e. turning a stream into a value — you need to wait for the last one. But it might never complete, you say. And you are indeed right. Then your promise will never get resolved and just be pending.
With observables this keeps happening to me over and over again: Just when I think I know what’s going on, some new quirk appears. And later it turns out that’s not a quirk but works as designed. I think that it’s because I see familiar concepts like `map filter toPromise` and I think:
“This is just like an array. Nothing to think about here, nothing to read about. It’s just like an array.”
And it’s not. It seems that the simple outlook of observables is what tricks us all…
I hope this one will help someone. It was certainly fun for me to “discover” :).