3 ms·
There's a way without exceptions. Use an ErrorT[Promise[A]] monad. I've done this in Scala before and it is so much simpler than the JavaScript convention you p
by pufuwozu 14y ago
There's a way without exceptions. Use an ErrorT[Promise[A]] monad. I've done this in Scala before and it is so much simpler than the JavaScript convention you pointed out.
It allows you to write code like this:
val query = "Brian"
val result = for {
db <- connectToDatabase
user <- userFromDatabase(db, query)
friends <- friendsFromDatabase(db, user.friends)
} yield friends
Whenever one of the functions above returns an error, the whole expression is that error. The outcome is either an error (if there was any) or the end value of Set[User]. No need to manually handle an error until you get to the end result.
- saryant 14y agoSimilar to this is the Scala fold convention. An example from the Play! Framework for form submissions: def submit = Action { implicit request => contactForm.bindFromRequest.fold( errors => BadRequest(html.contact.form(errors)), contact => Ok(html.contact.summary(contact)) ) }
- pfraze 14y agoThat's basically what the promises spec for Javascript gives you.
- pufuwozu 14y agoExactly. The promises spec defines the Promise monad. The problem is that JavaScript doesn't have monadic syntax, which would make the code a lot more readable.