这里有一个菜鸟问题...但首先,一些背景信息...
我已经开始使用 Express JS 编写一个应用程序,虽然我正在一点一点地掌握它的窍门,但我却遇到了困难......
我有 CodeIgniter 背景,在 CI 中,您在 Controller 中构建一个 $data 变量,其中包含需要传递到将呈现的页面的所有数据。
所以我试图在 Express 中做同样的事情......但我不知道如何正确地做到这一点。
例如,
我在名为“routes.js”的文件中有这段代码:
//when you navigate to domain.com/test
app.get('/test', function(req, res)
{
//object where i want to store all my data
var data = {};
//dynamically get the navigation menu
navigation_model.get_menu(function(err, result){
if(err) throw err;
//add the result, which is an object, to the data obj
data.navigation = result;
});
content_model.findAll(function(err, result){
if(err) throw err;
//add the result, which is an object, to the data obj
data.content = result;
});
//page that i want to send the data to
res.render('test_view',{data: this.data});
});
我遇到的问题是,由于 Node 的异步特性,当我渲染页面时,我的“数据”对象仍然没有收到来自模型的数据......
问题:
- 那么将数据放入“数据”对象的最佳方法是什么?
- 我是否必须将代码嵌套在回调函数中,嵌套在更多回调函数中,直到我的数据对象收到数据? (感觉适得其反)
非常感谢任何帮助!
最佳答案
data 为 null 的原因是因为函数 getMenu 和 findAll 是异步的,即渲染调用发生在 getMenu 和 findAll 能够完成其执行并填充 data 中的 approprivate 值之前。
修复此问题的一种方法是在第一个函数的回调中调用第二个函数,依此类推。
navigation_model.get_menu(function(err, result){
if(err) throw err;
//add the result, which is an object, to the data obj
data.navigation = result;
content_model.findAll(function(err, result){
if(err) throw err;
//add the result, which is an object, to the data obj
data.content = result;
res.render('test_view',{data: this.data});
});
});
更好的方法是使用 async库的并行或 waterfall 方法,以并行或使用 waterfall 顺序运行 geMenu 和 findAll,然后调用渲染方法。
关于javascript - 在node/express中构建数据对象并将对象传递给渲染模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24418789/