最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Promises in mysql2 - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Oct 3, 2019 at 12:03 Sky asked Oct 3, 2019 at 11:31 SkySky 951 gold badge1 silver badge8 bronze badges 1
  • The then function after the catch statement, is it meant to continue after the catch? – Tiisetso Tjabane Commented Oct 3, 2019 at 13:04
Add a comment  | 

2 Answers 2

Reset to default 10

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

Your promises can you chained a bit better, we have a problem with promises article helped me understand promises better.

You should avoid nesting promises and your case you can return the values of your promises to chain them.Great example about Promise chaining

I would flatten out your promise structure like this.

pool.getConnection(function(err, connection){
    if(err) throw err;
    var querySQL = "SELECT 1 FROM Categories LIMIT 1";
    return connection.promise().query(querySQL)
    .then((results)=> {
      if (results.rows!=undefined) {
        console.error("The table already exist");
        throw "The table already exist";
      }
      else {
        let querySQL = "CREATE TABLE Categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))";
        return connection.query(querySQL);
      }
    })
    .then((err, rows,) => {
        if(err) throw err;
        console.log("The table has been created");
        console.log(rows);
        return rows;
    })
    .catch(console.log)
    .finally(()=> {
      var querySQL = "SELECT x FROM y";
      return connection.promise().query(querySQL)
    })
    .then((results, error) => {
        /*
        More stuff
        */
        return nextPromise;
    //   .then( ()=> console.log("Promise ended") );

    })
    .then(() =>{
        console.log("Promise ended")
    })
  });
发布评论

评论列表(0)

  1. 暂无评论