node.js – express – res.render():正确的格式将variables提供给JSON参数?
我正在学node.js,所以忍受着我。
我试图创build一个node.js Web应用程序使用快速+玉,基本上只是一个线队列。 (IE取号码,排队,现在服务号码4 …除了4将是一个MySQL表字段)。 该页面将每5秒自动更新一次。 有三个行队列由页面(IE)处理:3000/1:3000/2:3000/3。
要清楚的是,我有这个应用程序的工作,但我想确保我正确地做到这一点,而不是只用差的方法来攻击它。
在我的index.js中我有标准的设置:
exports.bio = function(req, res){ res.render('index', { location: 'Biometrics', number: bio() }); }; exports.interview = function(req, res){ res.render('index', { location: 'Interview', number: interview() }); }; exports.docs = function(req, res){ res.render('index', { location: 'Documentation', number: doc() }); };
我目前也在index.js中调用“number:”JSON值的值。
var doc = (function() { //do javascript and data calls return a; }); var bio = (function() { //do javascript and data calls return a; }); var interview = (function() { //do javascript and data calls return a; });
我的问题是:什么是build议的方式来做到这一点,还是我在正确的轨道上?
只要函数doc(),bio()和interview()是同步的,这种方法就可以工作,但最有可能的情况不会是这样,特别是如果他们需要执行一些数据库访问的话。
如果这些函数是asynchronous的,那么你应该看起来像这样:
exports.docs = function(req, res){ // call the doc() function and render the response in the callback doc(function(err, number) { res.render('index', { location: 'Documentation', number: number }); }); };
doc()
函数如下所示:
var doc = (function(callback) { // This code very likely be async // therefore it won't return any value via "return" // but rather calling your function (callback) db.doSomething(someparams, callback); });
在db.doSomething()
里面会调用你的函数callback(err, theValue)
函数callback(err, theValue)
asynchronous的方式会是这样的:
exports.docs = function(req, res) { fetchSomeValueFromMysql(req.param('foo'), function (err, data) { if (err) { res.send(500, 'boom!'); return; } res.render('index', { location: 'Documentation', number: data }); }); };
说如果你在bio()
有一个asynchronous操作,
exports.bio = function (req, res) { bio(function (err, data) { if (!err && data) { res.render('index', { location: 'Biometrics', number: data }); } else { // handle error or no data res.render('error'); } }); } var bio = function(cb) { //do javascript and data calls cb(err, data); });
同样,有很多方法可以使这个工作。 但是,上面应该做的。