在对所有值进行排序之前呈现页面

时间:2019-03-27 09:51:30

标签: node.js

我认为渲染是在文件上的字符串搜索之前进行的,我尝试了不同的方法,但似乎无法正常工作。任何帮助将不胜感激。对Node.js来说是菜鸟。我试图获取用户ID并进行查询并获取所有数据,然后查看他是否在给定的任何列表中,并最终呈现该页面。

    const j = [];
let name = '';
const filename = [];
var ext = '';

module.exports = function(app, express) {

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/cusdetails', isLoggedIn, function (req, res) {

var cusid=req.body.cusid;

var insertQuerys = "SELECT * FROM customer WHERE cusid=? ORDER BY rowid DESC LIMIT 1";

     connection.query(insertQuerys,[cusid],
      function(err, rows){ 
        rows.forEach( (row) => {
          name=row.fncus;

});

fs.readdir('./views/iplist', function(err, files) {
    if (err)
        throw err;
    for (var index in files) {

        j.push(files[index])
    }

    j.forEach(function(value) {

var k = require('path').resolve(__dirname, '../views/iplist/',value);

fs.exists(k, function(fileok){
  if(fileok) {
        fs.readFile(k, function(err, content) {
           if (err) throw err;
            if (content.indexOf(name) > -1) {
                ext = path.extname(k);
                filename.push(path.basename(k, ext));
            }
        });
      }
      else {
        console.log(" FileNotExist ");
      }
    });
 });
}); 

            console.log(filename);
            res.render('cusdetails.ejs', {rows: rows, user:req.user , aml: filename });
});
     })

2 个答案:

答案 0 :(得分:1)

JavaScript是异步的。这意味着,如果您有一个带有回调的函数(即查询),则该回调将在未知时间异步调用,而其他代码将执行。

您需要查看一些有关如何处理回调的教程,以正确了解回调。另一种方法是使用async/await和/或promises。

基本上,如果您使用以下代码:

console.log("this will print first");

setTimeout(function () {
    console.log("this will print last");
}, 1000);

console.log("this will print second");

如果运行上面的代码,则顶级是同步执行的,因此,它首先调用console.log,然后执行setTimeout,这是同步的。它设置了一个超时,然后说“我准备好了”,并且代码继续到其他console.log。 1秒(1000毫秒)后,将执行setTimeout函数中的回调,然后才调用console.log。您不能让其余的代码以这种方式等待,您需要重组代码或读入Promise。

答案 1 :(得分:1)

您可以创建简单的Promise包装器,然后在async/await函数中使用它来暂停执行,直到resolved

// use mysql2 package as it provides promise, less work to write promise wrappers
const mysql = require('mysql2/promise');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// sample wrapper
function some(k) {
    // more advisable to have local variables, why do you need this to be array?
    var filename = [];
    return new Promise((resolve, reject) => {
      // doing this is also not recommended check nodejs documentation **fs.exists** for more info
      fs.exists(k, function(fileok){
        if(fileok) {
          fs.readFile(k, function(err, content) {
            if (err) reject(err);
            if (content.indexOf(name) > -1) {
              ext = path.extname(k);
              filename.push(path.basename(k, ext));
              resolve(filename)
            }
          });
        }
        else {
          // reject(new Error("FileNotExist"))
          console.log(" FileNotExist ");
        }
      });
    })
  }

// note the use of async
app.post('/cusdetails', isLoggedIn, async function (req, res) {

  var cusid=req.body.cusid;

  var insertQuerys = "SELECT * FROM customer WHERE cusid=? ORDER BY rowid DESC LIMIT 1";

    // using await to pause excution, waits till query is finished
    const [rows] = await connection.query(insertQuerys,[cusid])
    rows.forEach( (row) => {
      name=row.fncus;

  });

  // then you can
  var result = await some(k)
  ...

但是请注意,通过这种方式,您会失去concurrent执行的优势,因为它是种阻塞。如果一个调用的结果未在另一个调用中使用,则可以在parallelawait中执行结果以实现排序,例如

const [rows] = connection.query(insertQuerys,[cusid])

var result = some(k)

console.log(await rows) // do something
console.log(await result) // do something