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

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -