With the downside that I have absolutely no clue what this code does or how.
Once you get used to promises (it took me a couple of days) it's not confusing at all. It takes a bit of effort though. I remember when I first started programming none of the programs made any sense to me; as you said, I had absolutely no clue what the code did and how. But then I kept practicing and soon I understood how things work.
Yeah, I guess it's not fair for me to compare something I'm familiar with to something I'm not. I'm sure promises are easy to understand, but that API there does not look great.
Q has some utility functions around wrapping node style callbacks that make the code a bit shorter and arguably more easy to understand.
var Q = require('q');
function getUserFriends(userName) {
return Q.nfcall(db.users.findOne, {name:userName});
}
function foundOne(user) {
return Q.nfcall(db.friends.find, {userId:user.id});
}
function foundFriends(friends) { ... }
getUserFriends.then(foundOne).then(foundFriends);
Re:Callbacks are Pretty Okay
by prezjordan on Saturday August 17, 2013 @02:52PM
(#6229922)
That's much better, thanks for sharing
The cool thing about promises is that your methods are pretty portable. For example:
Can be rewritten (using q[0]) as: You'll see here that getUserFriends, foundOne, and foundFriends (which I left out) are now all portable and can be used elsewhere in the code for other purposes (because they are no longer tightly coupled).[0]: https://github.com/kriskowal/q