我怎么能等着开始工作呢

how can I wait to function

本文关键字:工作 开始 怎么能      更新时间:2024-03-03

我在node.js中写了一个html页面,我想放弃对数据的响应,但速度更快。。如何创建此函数sync?

app.get('/showGuides', function(req, res) {
text = fs.readFileSync(''start.html','utf8');
text = text + '<table border="1"><tr><td>id</td><td>name</td><td>last name</td><td>address</td><td>phone</td></tr>';
pool.getConnection(function(err, connection) {
    var sql = 'select * from guides;';
    console.log(sql);
    connection.query( sql, function(err, rows) {    
        if (rows.length  > 0) {
            rows.forEach(function(row) {
            console.log('add');
                text = text + '<tr><td>' + row.id + '</td>';
                text = text + '<td>' + row.name + '</td>';
                text = text + '<td>' + row.lastName + '</td>';
                text = text + '<td>' + row.address + '</td>';
                text = text + '<td>' + row.phone + '</td></tr>';
            });
        }
        connection.end();
    });
});
text = text + '</table>'
text = text + fs.readFileSync(''end.html','utf8');
res.end(text);
});

试试这个;

app.get('/showGuides', function (req, res) {
  fetchGuides(function (err, guides) {
    if (!err && guides) {
      var text = fs.readFileSync(''start.html', 'utf8');
      text += '<table border="1"><tr><td>id</td><td>name</td><td>last name</td><td>address</td><td>phone</td></tr>';
      text += guides;
      text += '</table>';
      text += fs.readFileSync(''end.html', 'utf8');
      res.end(text);
    } else {
      res.end('Unable to fetch guides');
    }
  });
});
function fetchGuides(cb) {
  pool.getConnection(function (err, connection) {
    var sql = 'select * from guides;';
    console.log(sql);
    var text = '';
    connection.query(sql, function (err, rows) {
      if (rows.length) {
        rows.forEach(function (row) {
          console.log('add');
          text += '<tr><td>' + row.id + '</td>';
          text += '<td>' + row.name + '</td>';
          text += '<td>' + row.lastName + '</td>';
          text += '<td>' + row.address + '</td>';
          text += '<td>' + row.phone + '</td></tr>';
        });
      }
      cb(err, text);
      connection.end();
    });
  });
}

Hum看起来您只是想呈现一个动态的html内容。在这种情况下,您可能真的更喜欢使用模板引擎,它会简单得多。由于您已经在使用Express,这应该会有所帮助:

  • 设置模板引擎:http://expressjs.com/api.html#app.engine
  • 渲染视图(使用伪html)http://expressjs.com/api.html#app.render并将结果传递给视图。基本上,您只需要调用res.render('mytable.html', { rows: rows });,在mytable.html中,就可以循环查询行,语法取决于模板引擎

无论如何,使用您的方法,您必须在查询回调中回复客户端请求(即res.end)。

我在之前的文章中更新了您的代码,使其能够工作。希望你能好好学习。然而,动态内容(如从数据库检索的结果)最好使用模板(如jadeejs)进行处理。

我将重构您的代码,以演示如何使用jade模板在express中实现这一点。为了让演示工作起来,我已经做了一些事情,你可以随意跳过/修改它们。:)

处理/showGuides请求的独立脚本:

var fs = require('fs');
var util = require('util');
var path = require('path');
var http = require('http');
var express = require('express');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// configure other middlewares you need
app.use(app.router);
process.on('uncaughtException', console.log);
var guides = {
  process: function process(req, res, next) {
    util.log('Received request to fetch guides');
    guides.fetch(function (err, guides) {
      req.guides = guides || [];
      next(err);
    });
  },
  fetch: function fetch(cb) {
    pool.getConnection(function (err, connection) {
      var sql = 'select * from guides;';
      connection.query(sql, function (err, rows) {
        cb(err, rows);
        connection.end();
      });
    });
  },
  render: function render(req, res, next) {
    res.locals.guides = req.guides;
    res.render('guides');
  },
  errors: function errors(err, req, res, next) {
    console.log(err);
    res.locals.errmsg = err.message;
    res.render('error');
  }
};
app.get('/showGuides', guides.process, guides.render, guides.errors);
var server = http.createServer(app).listen(3000);
// dummy pool -- you don't need this
var pool = {
  connection: {
    query: function (query, cb) {
      // dummy response -- simulate a db call
      setTimeout(function () {
        var dummies = [{
          id: 1,
          name: 'test',
          lastName: 'test',
          address: 'test',
          phone: 1234
        }, {
          id: 2,
          name: 'test2',
          lastName: 'test2',
          address: 'test2',
          phone: 12345
        }];
        cb(null, dummies);
      }, 500);
    },
    end: function () {
      // nothing to do
    }
  },
  getConnection: function (cb) {
    cb(null, pool.connection);
  }
};

现在我们需要添加一些玉模板,即guides.jadestart.jadeend.jadeerror.jade。将这些文件添加到目录views下。

观点/指南。翡翠:

include start
table(border="1", cellspacing="0", cellpadding="5px", width="50%")
  tr
    th id
    th name
    th last name
    th address
    th phone
  each row in guides
    tr
      td= row.id
      td= row.name
      td= row.lastName
      td= row.address
      td= row.phone
include end

views/start.jade

//- Contents from start.html
h3 Guides

views/end.jade

//- contents from end.html
p Guides data rendered.

views/error.jade

h3 Oops! An error occurred
p= errmsg

如果你是翡翠新手,那就从翡翠教程开始吧。如果您无法遵循上面代码中的任何内容,请告诉我。

你好!