初见

使用 bluebird将 mysql 异步代码同步化

2020-05-25  本文已影响0人  ag4kd
{
  "name": "vone-yunda-bc-api",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./app.js",
    "test": "mocha ./test/test.mysql.js"
  },
  "dependencies": {
    "bluebird": "^3.7.2",
    "chai": "^4.1.2",
    "chai-as-promised": "^7.1.1",
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "fabric-ca-client": "~1.4.0",
    "fabric-client": "~1.4.0",
    "grpc": "^1.6.0",
    "http-errors": "~1.6.3",
    "log4js": "latest",
    "mocha": "^5.2.0",
    "morgan": "~1.9.1",
    "mysql": "^2.18.1",
    "pug": "2.0.0-beta11"
  }
}

npm i

const option = {};
option.host = 'localhost';
option.user = 'root';
option.password = '';
option.port = 3306;
option.database = '';
// option.database = '';
module.exports = option;
const mysql = require('mysql');
const bluebird = require('bluebird');
const config = require('../config/config_mysql');
console.debug(config);
const pool = mysql.createPool(config);
const connect = bluebird.promisify(pool.getConnection, {context: pool});

/**
 *
 * @param sql sql 语句:CRUD
 * @returns {Promise<string|any>}
 */
const query = async function (sql) {
    try {
        let conn = await connect();
        const query = bluebird.promisify(conn.query, {context: conn});
        let res = await query(sql);
        conn.release();
        return JSON.parse(JSON.stringify(res));
    } catch (e) {
        console.error(e);
        return e.toString()
    }
};

module.exports.query = query;
const chai = require('chai');
const expect = chai.expect;
const should = chai.should();
const mysql = require('../libs/mysql');
describe('mysql pool', function () {
    it('query ', async function () {
        this.timeout(10000);
        let res = await mysql.query('select * from ioncwallet.activities');
        console.debug(res);
    });
});
上一篇 下一篇

猜你喜欢

热点阅读