我正在玩node.js和express。我有一個小服務器,它獲取sqlite內容並將所有內容發送到Jade模板。它工作正常使用此代碼:Node.js/Express異步函數
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);
但頁面加載,加載並沒有任何反應.. 我做了一些錯誤,但不知道那裏的時刻。如果有人有一個想法,它可能是偉大的;-)謝謝!
是的我知道,但這不是問題,我更新我的代碼到8080和同樣的問題。 – Silvering
@Sververing我更新了答案。 –
感謝您的幫助。不過同樣的問題:https://gist.github.com/anonymous/6fe238a282320f9707ea – Silvering