乐趣区

关于node.js:nodejs的mysql库promise化

promise 化

const mysql = require("mysql");
const pool = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "",
  port: "3306",
  database: "test",
});

const sqlQuery = (sql, values) => {return new Promise((resolve, reject) => {pool.getConnection((err, connection) => {if (err) {reject(err);
      } else {if (values) {connection.query(sql, values, (err, rows) => {if (err) {reject(err);
            } else {resolve(rows);
            }
            connection.release();});
        } else {connection.query(sql, (err, rows) => {if (err) {reject(err);
            } else {resolve(rows);
            }
            connection.release();});
        }
      }
    });
  });
};

应用

(async ()=>{const data = await sqlQuery(`select * from user limit 10`);
    console.log(data)
})()
退出移动版