async 配合mysql

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

 

posted @ 2017-07-03 17:02  webbky  阅读(667)  评论(0编辑  收藏  举报