【发布时间】:2016-01-02 22:53:23
【问题描述】:
我正在玩 node.js 和 express。我有一个小服务器,它获取 sqlite 内容并将所有内容发送到 Jade 模板。使用此代码可以正常工作:
var express = require('express');
var app = express();
app.set('view engine', 'jade');
var async = require('async');
var result_title = [];
var result_scope = [];
var result_benefits = [];
var result_technical = [];
app.use(express.static(__dirname + '/views'));
app.get('/product1', function(req, res){
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('products.db');
var check;
db.serialize(function() {
db.each("SELECT title, scope, body, technical_information FROM products", function(err, row) {
result_title.push(row.title);
result_scope.push(row.scope);
result_benefits.push(row.body);
result_technical.push(row.technical_information);
});
});
console.log(result_title[0]);
res.render("index", {title:result_title[0], scope:result_scope[0],benefits:result_benefits[0], technical_information:result_technical[0]});
db.close();
});
app.listen(8080);
我的问题是,当我转到页面 http://localhost/product1:8080 时,什么都没有显示。需要手动刷新页面才能加载内容!我的研究告诉我,我需要使用异步函数。我编辑了我的代码:
var express = require('express');
var app = express();
app.set('view engine', 'jade');
var async = require('async');
var result_title = [];
var result_scope = [];
var result_benefits = [];
var result_technical = [];
app.use(express.static(__dirname + '/views'));
app.get('/product1', function(req, res){
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('products.db');
var check;
async.series([
function(callback) {
db.serialize(function() {
db.each("SELECT title, scope, body, technical_information FROM products", function(err, row) {
result_title.push(row.title);
result_scope.push(row.scope);
result_benefits.push(row.body);
result_technical.push(row.technical_information);
});
});
},
function(callback) {
// console.log(result_title[0]);
res.render("index", {title:result_title[0], scope:result_scope[0],benefits:result_benefits[0], technical_information:result_technical[0]});
db.close();
}
], function(error, results) {
console.log('');
})
});
app.listen(8030);
但是网页正在加载,正在加载,但没有任何反应.. 我做错了什么,但暂时不知道在哪里。如果有人有想法,那就太好了;-) 谢谢!
【问题讨论】:
标签: javascript node.js asynchronous express pug