View profile

Debunking Common Complaints About JavaScript Promises

Debunking Common Complaints About JavaScript Promises
By Mastering JS Weekly • Issue #18 • View online
Promises are great. But there are plenty of arguments floating around the internet about why promises are limited. Here’s a few of those complaints, and why they’re baseless.

Promises Aren't Cancellable
The argument typically goes something like this: “promises aren’t usable because they’re uncancellable. What happens if I need to cancel an HTTP request when a user hits another key on an autocomplete? I should use RxJS.”
Newsflash: RxJS doesn’t cancel HTTP requests either. It simply gives you a method to ignore the response. The request still goes to the server. So if you want a way to let your users cancel a form submission after called `$http.put()`, RxJS won’t help you. However, ignoring a response is easy, regardless of whether you’re using promises or observables.
In general, cancelling a network operation is hard, and not guaranteed to work. What happens if you send an HTTP request to a server, the server processes it, and sends a response, and then you decide to cancel it?
But flat vs flatMap!
Functional programming purists tend to deride the fact that the `then()` function combines the notions of `flat()` and `flatMap()`. In simpler terms, there is no way for a promise to be fulfilled with another promise. If you call `Promise.resolve()` with another promise, JavaScript will tie the state of the new promise to the old promise.
In particular, this means there is no way for an async function to return a promise.
However, this behavior is what allows promise chaining, which is an elegant and practical pattern once you understand it. Also, in my experience, it is rare that you want an async operation to resolve to yet another async operation. However, in the odd case when you might need to do that, all you need to do is wrap your promise in a POJO:
You can make an async function return a promise
You can make an async function return a promise
Most Recent Tutorials
Did you enjoy this issue?
Mastering JS Weekly

Pragmatic web development. No bloatware allowed!

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue