node.js 并表达将 sqlite 数据传递给我的一个 View

标签 node.js express

在我的 app.js 中,我有以下尝试从 sqlite 数据库检索数据并将其传递到我的 View 之一:

app.get("/dynamic", function(req, res) {
    var db = new sqlite3.Database(mainDatabase)
    var posts = []

    db.serialize(function() {
        db.each("SELECT * FROM blog_posts", function(err, row) {
            posts.push({title: row.post_title, date: row.post_date, text: row.post_text})
        })
    })

    res.render("dynamic", {title: "Dynamic", posts: posts})
})

谁能告诉我我做错了什么。无论如何,posts 数组似乎都是空的。

编辑 我在关注 tutorial这解释了虽然插件有异步,但这个方法不是异步的

这是教程中的引述

Despite the callbacks and asynchronous nature of Node.js, these transactions will run in series, allowing us to create, insert, and query knowing that the statement prior will run before the current one does. However, sqlite3 provides a "parallel" wrapper with the same interface, but runs all the transactions in parallel. It just all depends on your current circumstances.

最佳答案

db 调用可能是异步的。这意味着您在他们返回数据之前进行渲染。

您需要弄清楚如何从您的查询中获取一个回调,并在该回调中呈现您的模板。

您似乎想要将第二个 complete 回调传递给 db.each() (谢谢 Jonathan Lonowski 的小费!)

var posts = [];
db.serialize(function() {
    db.each("SELECT * FROM blog_posts", function(err, row) {
        posts.push({title: row.post_title, date: row.post_date, text: row.post_text})
    }, function() {
        // All done fetching records, render response
        res.render("dynamic", {title: "Dynamic", posts: posts})
    })
})

这个想法是在任何异步代码的最后一个回调中渲染,这样你就拥有了你需要的一切。


关于node.js 并表达将 sqlite 数据传递给我的一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17954743/

相关文章:

node.js - Couchdb 套接字在 View 中挂起

javascript - PHP 包含的 Node.js 等价物是什么?

javascript - node.js 返回未定义的问题

node.js - ExpressJS - View 部分的自定义文件扩展名

javascript - Mongodb 到 Android 应用程序

mysql - Node sql语法错误

node.js - 为什么我的 Nginx 反向代理 node.js+express 服务器重定向到 0.0.0.0?

测试时出现 Typescript、Express、Mocha 和 Chai 错误

javascript - 使用 JavaScript/Node.js 实现插件架构

javascript - Angular 代码不适用于 express