Search code examples
javascriptmysqlnode.jsmysql2

Promises in mysql2


Recently I wanted to learn Node.js to help me to find a job so I started a web scraping application.

I started with mysql package but after writing the code I didn't have in mind this is an asynchronus proccess.

Then I found mysql2 with promises but I'm not sure if I understand how to use them properly and I'm doing a bad practice.

Here is my code


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") );

      });

    });

The question is if I'm doing good chaining promises like that or there is another way, because this code is to create the tables of the database if there isn't any and then insert data. After the first insert every time the website updates his content, I'll create a temporary table to check if there is a new category, object... etc so this leads me to more promise inside this promises.


Solution

  • I'd suggest trying the async/await syntax, it keeps things a little more readable.

    This should do what you wish:

    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();