mysql2 中的承诺

Pun*_*Sky 2 javascript mysql node.js mysql2

最近我想学习 Node.js 来帮助我找到一份工作,所以我开始了一个网页抓取应用程序。

我从 mysql 包开始,但在编写代码后我没有想到这是一个异步过程。

然后我发现 mysql2 有承诺,但我不确定我是否理解如何正确使用它们,而且我的做法很糟糕。

这是我的代码


const mysql = require('mysql2');

const pool = mysql.createPool({ ... });

var categorias = [];
var querySQL;

/*
Here goes web scraping stuff not needed in this question
*/

pool.getConnection(function(err, connection){

      if(err) throw err;

      querySQL = "SELECT 1 FROM Categories LIMIT 1";

      connection.promise().query(querySQL).then(([rows,fields])=> {

        if (rows!=undefined) {
          console.log("The table already exist");
        }else {

          querySQL = "CREATE TABLE Categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))";

          connection.query(querySQL,function(err,rows,field){

            if(err) throw err;

            console.log("The table has been created");
            console.log(rows);

          });

        }

      })
      .catch(console.log)
      .then( ()=> {

        querySQL = "SELECT x FROM y";

        connection.promise().query(querySQL).then(([rows,fields])=> {

          /*
          More stuff
          */

        })
        .catch(console.log)
        .then( ()=> console.log("Promise ended") );

      });

    });

Run Code Online (Sandbox Code Playgroud)

问题是我是否在做好这样的链接承诺,或者还有另一种方式,因为如果没有任何表,这段代码将创建数据库的表,然后插入数据。每次网站更新他的内容时第一次插入后,我将创建一个临时表来检查是否有新的类别、对象......等等,这让我在这个承诺中得到更多的承诺。

Ter*_*nox 5

我建议尝试 async/await 语法,它使事情更具可读性。

这应该做你想做的:

async function tableExists(pool, tableName) {
    try {
        const query = `SELECT 1 FROM ${tableName} LIMIT 1;`;
        await pool.execute(query);
        return true;
    } catch (err) {
        return false;
    }
}

async function createdb() {
    const mysql = require('mysql2/promise');

    const config = {
        host: 'host',
        user: 'username',
        password: 'password_goes_here',
        database: 'some_database'
    }

    const pool = mysql.createPool(config);

    let tableOk = await tableExists(pool, "categories");
    if (tableOk) {
        console.log("Table 'Categories' already exists.");
        return;
    }
    console.log("Table 'Categories' does not exist, creating...");

    try { 
        const createQuery = "CREATE TABLE Categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20));";
        await pool.execute(createQuery);
        console.log("Table created successfully.");
    } catch (err) {
        console.error("Table creation failed:", err);
    }

    pool.end();
}

createdb();
Run Code Online (Sandbox Code Playgroud)