Skip to content

Instantly share code, notes, and snippets.

@steveinatorx
Created November 19, 2016 00:28
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 steveinatorx/b37ee15260a6586010d53a90a21cdd37 to your computer and use it in GitHub Desktop.
Save steveinatorx/b37ee15260a6586010d53a90a21cdd37 to your computer and use it in GitHub Desktop.
asynchronous require in node
/* i needed to load a bunch of static filter arrays into an api route in node - express -
so rather than making that DB call every time i ran the
api route here is a keen pattern to require async - use require with a callback.
This is a quick and easy way to do "poor man's server caching" with node in a server context
*/
require('./apiHelper').getOptFilter(function(err, filter){
console.log('i got the filter now load the rest of my route/module', filter);
});
//then in your helper module
module.exports = {
getOptFilter: function(callback) {
//do something asyncy
filterCollection.find({}).exec(function(err, filterObjs) {
//use your callback and send err , your data
callback(err,filterObjs.map(function(v){return v.code;}));
});
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment