Skip to content

Instantly share code, notes, and snippets.

@andrewluetgers
Created August 17, 2013 17:17
Show Gist options
  • Save andrewluetgers/6257858 to your computer and use it in GitHub Desktop.
Save andrewluetgers/6257858 to your computer and use it in GitHub Desktop.
In response to http://andrewkelley.me/post/js-callback-organization.html I believe that the convention of next(err, val) is that if err is truthy it will get handled if not then you expect data in the second arg. I often see code that adds extra checks for if (err != null) but is not necessary, you can just pass in the error with your data if th…
var async = require('async');
function getUserFriends(userName, next) {
db.users.findOne({name:userName}, foundUser);
function foundUser(err, user) {
err ? next(err) : getFriendsById(user.id, gotFriends);
function gotFriends(err, friends) {
if (err || user.type != 'power user') {
next(err, friends);
} else {
async.map(friends, getFriendsById, addFriendsOfFriends);
}
function addFriendsOfFriends(err, friendsOfFriends) {
for2dArray(friendsOfFriends, function(row, val) {
if (val && friends.indexOf(val) != -1) {
friends.push(val);
}
});
next(err, friends);
}
}
}
}
function getFriendsById(userId, next) {
db.friends.find({userId:userId}, next);
}
function for2dArray(twoDimensionalArray, fn) {
for (var i = 0; i < twoDimensionalArray.length; i++) {
for (var j = 0; j < twoDimensionalArray[i].length; j++) {
fn(twoDimensionalArray[i], twoDimensionalArray[i][j], i, j);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment