javascript - Running asynchronous functions once within express -
is correct way have asynchronous functions run once within express? don't want function have run on every route. i'm looking express-friendly way this.
var packagejson = false app.use(function(req, res, next){ if(req.packagejson) return next() if(packagejson){ req.packagejson = packagejson return next() } return fs.readfileasync("./package.json", "utf8") .then(json.parse) .then(function(data){ packagejson = data req.packagejson = data return next() }) })
i wouldn't run asynchronous function within first call route, do
var packagejson = fs.readfileasync("./package.json", "utf8").then(json.parse); app.use(function(req, res, next){ if (req.packagejson) return next(); else packagejson.then(function(data){ req.packagejson = data; return next(); }); }); but don't forget proper error handling, if packagejson promise rejected route might hang infinitely.
Comments
Post a Comment