Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

For the curious, the equivalent example from the OP using promises[1]:

  function getUserFriends(userName) {
    return db.users.findOne({ name: userName }).then(function (user) {
      return db.friends.find({ userId: user.id });
    });
  }
[1]: http://promises-aplus.github.io/promises-spec/


Promises + CoffeeScript really hits the sweet spot for me:

    getUserFriends = (userName) ->
      db.users.findOne(name: userName).then (user) ->
        db.friends.find userId: user.id
Or prezjordan's example:

    getUserFriends = (userName) ->
      db.users.findOne(name: userName)
        .then (user) ->
          db.friends.find userId: user.id
        .then(function (friends) ->
          somethingAsync(friends)
The concise function syntax and implicit "return" really helps.

If that's not good enough you can implement higher level control flow abstractions much more nicely than with raw callbacks, e.x. https://github.com/tlrobinson/q-step

    getUserFriends = (userName) ->
      QStep(
        ->
          db.users.findOne name: userName
        (user) ->
          db.friends.find userId: user.id
        (friends) ->
          somethingAsync friends
      )


It's more obvious if you have multiple levels.

  function getUserFriends(userName) {
    return db.users.findOne({ name: userName })
      .then(function (user) {
        return db.friends.find({ userId: user.id });
      })
      .then(function (friends) {
        return somethingAsync(friends);
      });
  }


I don't ever write code like this personally. The multiple levels make it more difficult to reason about, IMO.


Thanks for the comparison, I should probably add promise syntax to the landing page to cover more bases.

I think a useful case would be the trickier stuff where Kal really shines. For example, doing async stuff inside of loops, conditional calls (where some paths need async waits and others don't) and error handling. I also think the Kal syntax might appeal to people who are less experienced with JavaScript and it's more eclectic features.


Promises are a completely sufficient solution to handle asynchronous code in my opinion and there are already several great libraries for this in JavaScript. I don't get it why would I want to switch to a new language just because of that one feature.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: