javascript - Cached asynchronous Node.js objects, avoiding callback hell -
i've got express app relies on database stores json object used app's main configuration object. i'd cache object don't have keep going database up. however, i'd way invalidate cached object if new configuration object inserted database, , have app pick new object without restart. on top of that, i'd of without digging deep callbacks
at outset, example of code (this contrived, don't worry db design or premise -- it's not real). assume users can assigned list of roles, stored in "config" object:
// config.js var config; module.exports = function(cb) { if(config != null) { cb(config); } else { db.query('select data config', function(res) { config = json.parse(res.data); cb(config); }) } } // users.js var config = require('config'); var roles; config(function(data) { roles = data['user roles']; // cache roles lifetime of application, doesn't allow invalidation }); module.exports = { get: function(id, cb) { db.query('select name, roleids user id = $1', [id], function(res) { var userroles = _.map(res.roleids, function(roleid) { return roles[roleid]; }); cb({ 'name': res.name, 'roles': userroles }); }); } };
this code caches user role definitions in users.js
when app started, there's no way me invalidate cache when i've updated database new config data. i've done situation i've instead wrapped contents of get
function inside call config()
, need pattern numerous places in code, , seems clunky have that.
the ideal scenario, think, (using either callbacks or promises -- i'm fine either):
// users.js var config = require('config'); module.exports = { get: function(id, cb) { db.query('select name, roleids user id = $1', [id], function(res) { var userroles = _.map(res.roleids, function(roleid) { return config('user roles')[roleid]; // call either use cached version or call out db }); cb({ 'name': res.name, 'roles': userroles }); }); } };
it seems real issue i'm grappling synchronousness. want function call config
(and perhaps underlying call db) lazily load/cache result, still provide value in-place whenever need it, without overly nested callback structures/too wrapping of code.
hopefully makes sense. if not, let me know , i'll try clarify.
Comments
Post a Comment