Unnesting Node database calls

后端 未结 5 869
半阙折子戏
半阙折子戏 2021-01-19 03:27

I have an ordinary

var express = require(\'express\')

Node express www page, using session, pug, etc as usual. My db calls

var         


        
5条回答
  •  走了就别回头了
    2021-01-19 03:43

    If you're trying to use MySQL with Nodejs, the module you should be looking for is mysql2 rather than mysql.

    mysql2 provides a promise based approach and is a much refined version of mysql module for nodejs.

    For example, for executing a query,

    1. in mysql
    con.query(sql_query, (err, rows, field)=>{ //some code here }
    
    1. in mysql2, you can use the async approach as well as promise approach. Also, prepared statements in mysql2 are more easier than mysql.
    //async approach
    class A {
       static async fn(sql, params){
          const [data] = await con.execute(sql, [params]);
        return data;
        }
    }
    
    //promise approach remains same as **mysql** itself.
    

    Here's the documentation for mysql2 & more docs

提交回复
热议问题