简体   繁体   English

如何使用express.js返回mySql查询的结果?

[英]How to return the results of mySql query using express.js?

I am trying to get the results of my simple SELECT command to the index.js file, where I would like to have all records separated in a array.我正在尝试将简单的 SELECT 命令的结果获取到 index.js 文件,我希望在该文件中将所有记录分隔在一个数组中。 If I print the results in the database.js the JSON.parse just work fine.如果我在 database.js 中打印结果,JSON.parse 就可以正常工作。 But if I want to return them and get them into the index.js where I need them, I always get undefined when I print it.但是如果我想返回它们并将它们放入我需要它们的 index.js 中,我在打印它时总是得到 undefined 。

index.js CODE index.js代码

const express = require('express');
const app = express();
const database = require('./database');

app.use(express.json());

app.use(express.urlencoded());

app.use(express.static('public'));

app.get('/form', (req,res) =>{
    res.sendFile(__dirname + '/public/index.html' );
    console.log(req.url);
    console.log(req.path);
})


app.listen(4000, () =>{
    console.log("Server listening on port 4000");
    database.connection;
    database.connected();
    //console.log(database.select());
    let results = [];
    //results.push(database.select('username, password'));
    let allPlayer = database.select('username');
    console.log(allPlayer);
});

database.js CODE数据库.js代码

let mysql = require('mysql');

const connection = mysql.createConnection({
    host: 'localhost',
    database: 'minigames',
    user: 'root',
    password: 'root'
});
    
function connected(){
    connection.connect((err) => {
        if(err) throw err;
        console.log("Connected...");
    })
}

function select(attribute){
    let allPlayer = [];
    let sql = `SELECT ${attribute} FROM player`;
    let query = connection.query(sql, (err, result, field) => {
    
    if(err) throw err;
        return Object.values(JSON.parse(JSON.stringify(result)));
    })
}
module.exports = {connection, connected, select};

Understand that one of the main things that make JavaScript different from other languages is that it's asynchronous , in simple terms meaning code doesn't "wait" for the code before it to finish executing.理解使 JavaScript 与其他语言不同的主要因素之一是它是异步的,简单来说意味着代码在完成执行之前不会“等待”代码。 Because of this, when you're trying to query a database, which takes some time, the code after it gets impatient and executes regardless of how to the query is doing.因此,当您尝试查询数据库时,这需要一些时间,无论查询如何进行,它之后的代码都会变得不耐烦并执行。 To solve this problem, the mysql package utilizes callbacks , which allows you to pass a function to it to execute once the query is finished with the queries result.为了解决这个问题, mysql package 使用回调,它允许您将 function 传递给它,以便在查询完成并获得查询结果后执行。
Because the library operates on callbacks, it doesn't return anything;因为库在回调上运行,所以它不返回任何东西; that seems quite problematic for using it somewhere else, doesn't it?在其他地方使用它似乎很有问题,不是吗?

To solve this problem, we can make our own callback.为了解决这个问题,我们可以自己做回调。 Or better yet, use the newer JavaScript feature called promises, where you can basically "return" anything from a function, even when you're in a callback.或者更好的是,使用称为 promises 的更新的 JavaScript 功能,您基本上可以从 function 中“返回”任何内容,即使在回调中也是如此。

Let's implement it with the query:让我们用查询来实现它:

function select(attribute) {
  return new Promise((resolve, reject) => {
    let sql = `SELECT ${attribute} FROM player`;
    let query = connection.query(sql, (err, result, field) => {
      if(err) return reject(err);
      resolve(Object.values(JSON.parse(JSON.stringify(result))));
    });
  });
}

To "return" from a promise, we pass a value to the resolve function. To throw an error, we call the reject function with the error as the argument.要从 promise“返回”,我们将一个值传递给resolve function。要抛出错误,我们调用reject function 并将错误作为参数。

Our new function is rather easy to use.我们的新 function 相当易于使用。

select("abcd").then(result => {
  console.log("Result received:", result);
}).catch(err => {
  console.error("Oops...", err);
});

You might look at this code and go, "Wait a minute, we're still using callbacks. This doesn't solve my problem!"你可能会看看这段代码和 go,“等一下,我们仍在使用回调。这不能解决我的问题!”
Introducing async / await , a feature to let you work just with that.引入async / await ,这是一项让您可以使用它的功能。 We can call the function instead like this:我们可以这样调用 function:

// all 'await's must be wrapped in an 'async' function
async function query() {
  const result = await select("abcd"); // woah, this new await keyword makes life so much easier!
  console.log("Result received:", result);
}
query(); // yay!!

To implement error catching, you can wrap you stuff inside a try {...} catch {...} block.要实现错误捕获,您可以将内容包装在try {...} catch {...}块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM