async 配合mysql

时间:2023-03-08 17:39:38
async-db.js
const mysql = require('mysql')
const pool = mysql.createPool({
host : '127.0.0.1',
user : 'root',
password : '123456',
database : 'my_database'
}) let query = function( sql, values ) {
return new Promise(( resolve, reject ) => {
pool.getConnection(function(err, connection) {
if (err) {
reject( err )
} else {
connection.query(sql, values, ( err, rows) => { if ( err ) {
reject( err )
} else {
resolve( rows )
}
connection.release()
})
}
})
})
} module.exports = { query }
//使用
const { query } = require('./async-db')
async function selectAllData( ) {
let sql = 'SELECT * FROM my_table'
let dataList = await query( sql )
return dataList
} async function getData() {
let dataList = await selectAllData()
console.log( dataList )
} getData()