View Single Post
Somnid
Member
(07-31-2017, 04:18 AM)
Somnid's Avatar

Originally Posted by Kieli

I'm looking at promises, and I do not see their purpose at all. Like, asynchronous callbacks are much easier to use and understand. What the hell are "thens" and "catches"? Is JS promise trying to do a poor man's version of try-catch?

I think Kalnos generally got the gist of promises across but to go even further:

Try catch is generally an anti-pattern that can also be fixed the same way. For example many functional-based languages do not throw exceptions and use algebraic types to represent success or failure typically called "Result". This forces you not only to handle exceptions as the caller but also greatly simplifies the code because you always know what is expected and you can chain them. If you implemented one in js it might look like this:

Code:

parseInt(x)
  .andThen(x => x * 2)
  .andThen(x => 1/x)
  .andThen(x => x.toString())
  .orElse(e => `invalid input: ${e}`)
We can do the same thing to eliminate null with a type typically called "Option" or "Maybe" (this looks almost the same as result except it does not have an error type so the else function just excepts no parameters):

Code:

dictionary.get(x)
  .andThen(x => x.toString())
  .orElse(() => `invalid input: ${e}`)
You're probably already familiar with method chaining for lists:

Code:

list.filter(x => x > 10)
  .map(x => x * 2)
and if you've used RxJx you'll see the same thing happening for observables.

So then why not with an async result?

In general this generic structure that wraps values is called a monad and is heavily used in functional programming. Try out a functional language like Elm (which is designed for front-end web) and you might get an appreciation for it.