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

35次阅读

共计 581 个字符,预计需要花费 2 分钟才能阅读完成。

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

正文完
 0