Here’s a situation I need to filter some restaurants by location, then when I get the results I need to filter those restaurant’s items by price, then when the price filter is done I need to filter those items by tag names.
you frequently end up with a bunch of nested async calls:
restsAtLoc(loc, function(rests){
filterItemsByPrice(items, function(filtered){
filterItemsByTagNames(items, tags, function(filtered){
//Finally done
}
}
}
the best approach in this situation is to abstract everything so you only work with the highest level:
callbackHellFood(loc, price, tags, function(food){
eat(food)
});
// if you see .then(fn) it is a 'promises' syntax: function restsAtLoc(locc, callback){ db.find('rests').filterBy(loc).then(callback) }
// you can also directly invoke a callback to signify the end of a long operation: function filterItemsByPrice(items, callback){ items.sort(fn); ... callback(items.slice(20)); }
function filterItemsByTagNames(items, tagnames, callback){ var results = []; items.forEach(function(item){ item.tags.forEach(function(tag){ if(tagnames.indexOf(tag) !== -1){ results.push(item); } }; }); }