gpt4 book ai didi

javascript - node.js - 表达 - res.render() : Correct format for feeding variables into the JSON parameter?

转载 作者:行者123 更新时间:2023-11-30 12:52:00 26 4
gpt4 key购买 nike

我正在学习 node.js,请耐心等待。

我正在尝试使用 express+jade 创建一个 node.js Web 应用程序,它基本上只是一个队列。 (即拿一个号码,排队等候,现在服务号码 4 ......除了 4 将是一个 mysql 表字段)。该页面将每 5 秒自动更新一次。页面 (I.E) 处理了三个行队列:300​​0/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;
});

我的问题是:执行此操作的推荐方法是什么,或者我是否在正确的轨道上?

最佳答案

只要函数 doc()、bio() 和 interview() 是同步的,这就可以工作,但很可能情况并非如此,尤其是当它们需要执行某些数据库访问时。

如果这些函数是异步的,那么你应该看起来像这样:

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)

关于javascript - node.js - 表达 - res.render() : Correct format for feeding variables into the JSON parameter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com