5 ms·
Right, but now your functions are very tightly coupled to each other. The indentation might be nicer, but functionally it's just misleading. The cool thing abo
by prezjordan 13y ago
Right, but now your functions are very tightly coupled to each other. The indentation might be nicer, but functionally it's just misleading.
The cool thing about promises is that your methods are pretty portable. For example:
function getUserFriends(userName, next) {
db.users.findOne({name:userName}, foundOne);
function foundOne(err, user) {
if (err != null) return next(err);
db.friends.find({userId:user.id}, foundFriends);
}
function foundFriends(err, friends) {
if (err != null) return next(err);
return next(null, friends);
}
}
Can be rewritten (using q[0]) as:
var Q = require('q');
function getUserFriends(userName, next) {
var deferred = Q.defer();
db.users.findOne({name:userName}, deferred.makeNodeResolver());
return deferred.promise;
}
function foundOne(user) {
var deferred = Q.defer();
db.friends.find({userId:user.id}, deferred.makeNodeResolver());
return deferred.promise;
}
function foundFriends(friends) { ... }
getUserFriends.then(foundOne).then(foundFriends);
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 https://github.com/kriskowal/q
- StavrosK 13y agoWith the downside that I have absolutely no clue what this code does or how.
- DrJokepu 13y agoOnce 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.
- StavrosK 13y agoYeah, 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.
- modiho 13y agoQ 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);
- prezjordan 13y agoThat's much better, thanks for sharing