Hacker News new | comments | show | ask | jobs | submit login

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.



Similar 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))
      )
    }


That's basically what the promises spec for Javascript gives you.


Exactly. 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.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: