美文网首页初见
使用 bluebird将 mysql 异步代码同步化

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

作者: ag4kd | 来源:发表于2020-05-25 20:35 被阅读0次
    • package.json
    {
      "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;
    
    • mysql.js
    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);
        });
    });
    

    相关文章

      网友评论

        本文标题:使用 bluebird将 mysql 异步代码同步化

        本文链接:https://www.haomeiwen.com/subject/ujqpihtx.html