javascript - node pg callback event -
hey basicly im writing web appliaction ,i didint handle evrything in app.js did make 1 script called event.js handle page functions , export them ,my problem working great till didint need list database,i know not elegant ,but did tryed whit events , whit callbacks ...here code whitout call or ,in case first time cant load nothing,for second render have values..
//app.js app.get('/page',events.page); //event.js exports.page = function(req,res,next) { if (name == 'accounting'){ if (req.session.ulevel == 0) { name='index'; mg='notauthed'; show='nothing'; } else { show='accinfo'; name == 'accounting'; console.log('asdasdasdinfoooo'); pg.connect(connectionstring, function(err, client) { client.on('drain', client.end.bind(client)); client.query('select * newtest5 id=$1',['uid'] , function(err,results){ dlogin=results.rows[0].username; did=results.rows[0].id; dpwd=results.rows[0].password; demail=results.rows[0].email; dregdate=results.rows[0].regdate; drule=results.rows[0].rights; dmoney=results.rows[0].balance; // move render here }); }); res.render('index', { title: name, dplay:show, dbname:dlogin, dbid:did, dbpwd:dpwd, dbrule:drule, dbregd:dregdate, dbemail:demail, username:req.session.user, uid:req.session.uid, user:req.session.user, right:req.session.ulevel, content:contents[name], msg:msgs[mg] }), console.log('data:'+dlogin); } } }
my object when name accounting in code ,i render 1 page ,whit loaded information ,not before working,basicly routing in app js ,and evry function ,and renders totaly exported event js ,its basicly working well,just problem ..render runing before database read finished..somehow need make render wait data read end,then execute render.
your indentation made impossible see going on. reindented it. when call pg.connect(str, callback)
, pass callback define dlogin
etc. after call pg.connect
call res.render()
! javascript engine waits no man. proper way put res.render()
inside innermost callback. make sure response isn't sent until have defined dlogin
etc.
you may use res.locals
if want set variables jade use (or presumably other template engines)
//app.js app.get('/page',events.page); //event.js exports.page = function(req,res,next) { if (name == 'accounting'){ if (req.session.ulevel == 0) { name='index'; mg='notauthed'; show='nothing'; } else { show='accinfo'; name == 'accounting'; console.log('asdasdasdinfoooo'); pg.connect(connectionstring, function(err, client) { client.on('drain', client.end.bind(client)); client.query('select * newtest5 id=$1',['uid'] , function(err,results){ res.locals.dlogin=results.rows[0].username; res.locals.did=results.rows[0].id; // etc... console.log('data:'+res.locals.dlogin); // ... gets set here, when callback run res.render('index'); }); }); console.log('data:'+res.locals.dlogin); // undefined after defining callback, until callback run // pg.connect() has been run, not callback, yet } } }
Comments
Post a Comment