Skip to content

Instantly share code, notes, and snippets.

@plato-cambrian
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plato-cambrian/110d94a720212d50c9c2 to your computer and use it in GitHub Desktop.
Save plato-cambrian/110d94a720212d50c9c2 to your computer and use it in GitHub Desktop.

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); } }; }); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment