node.js - NodeJs reload data from file to view -
my app fetching data external file , display on ejs view. user can change data post method. should saved , displayed on view. new data displayed after second click on form submit. not first.
how can change it?
var info; fetchtag(); function fetchtag() { fs.readfile('tag.js','utf8',function(err,data){ if(err){return console.log(err)}; info = data; }); } router.get('/',function(req,res){ res.render('index',{tag: info}); }); router.post('/tag',function(req,res){ fs.writefile('tag.js',req.body.tag); fetchtag(); res.redirect('/'); });
fs.writefile()
asynchronous function. means isn't finished running before .post()
route calls fetchtag.
then, because fethctag()
function asynchronous, won't finish until after redirect route. try making fetchtag()
promise based.
function fetchtag() { return new promise((resolve, reject)=>{ fs.readfile('tag.js','utf8',function(err,data){ if(err){ reject(err) } else { info = data; resolve(info); } }); }); } router.post('/tag',function(req,res){ fs.writefile('tag.js', req.body.tag, (err) => { if (err) throw err; console.log('the file has been saved!'); fetchtag().then((info)=>{ res.redirect('/'); }).catch((err)=>throw err); });
if go route, , think better, can change way handle info
, rendering page.
Comments
Post a Comment