async/await封装使用mysql

前言

由于mysql模块的操作都是异步操作,每次操作的结果都是在回调函数中执行,现在有了async/await,就可以用同步的写法去操作数据库

Promise封装mysql模块

Promise封装 ./async-db

  1. const mysql = require('mysql')
  2. const pool = mysql.createPool({
  3. host : '127.0.0.1',
  4. user : 'root',
  5. password : '123456',
  6. database : 'my_database'
  7. })
  8. let query = function( sql, values ) {
  9. return new Promise(( resolve, reject ) => {
  10. pool.getConnection(function(err, connection) {
  11. if (err) {
  12. reject( err )
  13. } else {
  14. connection.query(sql, values, ( err, rows) => {
  15. if ( err ) {
  16. reject( err )
  17. } else {
  18. resolve( rows )
  19. }
  20. connection.release()
  21. })
  22. }
  23. })
  24. })
  25. }
  26. module.exports = { query }

async/await使用

  1. const { query } = require('./async-db')
  2. async function selectAllData( ) {
  3. let sql = 'SELECT * FROM my_table'
  4. let dataList = await query( sql )
  5. return dataList
  6. }
  7. async function getData() {
  8. let dataList = await selectAllData()
  9. console.log( dataList )
  10. }
  11. getData()