Javascript nodejsmysql查询同步? 我需要在nodejs和mysql中使用select语句。在这之后,我想要“console.log()”-一些东西。

Javascript nodejsmysql查询同步? 我需要在nodejs和mysql中使用select语句。在这之后,我想要“console.log()”-一些东西。,javascript,mysql,sql,node.js,Javascript,Mysql,Sql,Node.js,我的代码: con.query("SELECT l.id, l.name FROM country l ORDER by l.id", function(err, land, fields) { console.log(land); }); console.log("Hello World"); 我的输出: "Hello World" RowDataPackets 我需要这个输出: RowDataPackets "

我的代码:

con.query("SELECT l.id, l.name FROM country l ORDER by l.id", function(err, land, fields)
{
     console.log(land);
});
console.log("Hello World");
我的输出:

"Hello World"
RowDataPackets
我需要这个输出:

RowDataPackets
"Hello World"

我该怎么做呢?

查询完成后要显示的任何内容都必须出现在
.query()函数的回调中:

{
     console.log(land);
     console.log("Hello World");
});

正如您所发现的,
.query()
会立即返回其调用者,并在稍后通过调用回调函数让您知道这已完成。

对于顺序执行,您需要使用async Wait

您可以这样编写数据库文件

        const util = require('util')
        const mysql = require('mysql')
        const pool = mysql.createPool({
          connectionLimit: 10,
          host: 'localhost',
          user: 'root',
          password: 'password',
          database: 'my_database'
        })

        // Ping database to check for common exception errors.
        pool.getConnection((err, connection) => {
          if (err) {
            if (err.code === 'PROTOCOL_CONNECTION_LOST') {
              console.error('Database connection was closed.')
            }
            if (err.code === 'ER_CON_COUNT_ERROR') {
              console.error('Database has too many connections.')
            }
            if (err.code === 'ECONNREFUSED') {
              console.error('Database connection was refused.')
            }
          }

          if (connection) connection.release()

          return
            })

            // Promisify for Node.js async/await.
            pool.query = util.promisify(pool.query)

            module.exports = pool
然后只要你能像这样导入后使用

        const db= require('./database')
        route.post('/users',async function(){
              try{
                let result = await db.query('SELECT l.id, l.name FROM country 
       l ORDER by l.id');
             }catch(err){
              console.log(err);
             }
         });
了解异步等待:


了解
async/await
以及如何不这样做?如果您想要顺序执行,则需要使用async await了解Javascript中的大多数客户机-服务器操作(如SQL查询)本质上是异步的。您可以通过回调、承诺和/或异步/等待来管理异步性。(async/await基本上是一种易于阅读的承诺语法)。如果您不想处理异步操作,唯一的方法就是避免使用Javascript。