4 ms·
For the curious, the equivalent example from the OP using promises[1]: function getUserFriends(userName) { return db.users.findOne({ name: userName }).th
by mjackson 13y ago
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/ http://promises-aplus.github.io/promises-spec/
- prezjordan 13y agoIt'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); }); }
- mjackson 13y agoI don't ever write code like this personally. The multiple levels make it more difficult to reason about, IMO.
- rzimmerman 13y agoThanks 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.
- tlrobinson 13y agoPromises + 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 https://github.com/tlrobinson/q-step getUserFriends = (userName) -> QStep( -> db.users.findOne name: userName (user) -> db.friends.find userId: user.id (friends) -> somethingAsync friends )
- pkorzeniewski 13y agoPromises 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.