如何在node.js中实现promise代码段来代替mysql客户端

ktecyv1j  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(386)

我最初寻求解决方案的目的是因为,我想使用observates,因为我想获得Angular ui上的实时数据。但这里的问题是我得到的sql错误-->太多的sql连接。所以每次查询访问数据库后,我都需要关闭连接。这在我的代码中没有发生。所以我搜索了可用的代码找到了这个-
https://codeburst.io/node-js-mysql-and-promises-4c3be599909b
节点代码-

const mysql = require( 'mysql' );
  class Database {
   constructor( config ) {
    this.connection = mysql.createConnection( config );
    }
   query( sql, args ) {
    return new Promise( ( resolve, reject ) => {
        this.connection.query( sql, args, ( err, rows ) => {
            if ( err )
                return reject( err );
            resolve( rows );
        } );
     } );
    }
   close() {
    return new Promise( ( resolve, reject ) => {
        this.connection.end( err => {
            if ( err )
                return reject( err );
            resolve();
        } );
    } );
    }
    }

现在我想在我的nodejs文件中实现上面的代码,它的代码是-
[来自MyAngular的http请求首先命中controller.js文件,然后从那里命中service.js文件]
更新
Jmeter 板.controller.js

var express = require('express');
  var router = express.Router();
  var dashboardService = require('../../services/SYSTEM
   /dashboard.service');
   var app = express();

    router.post('/abcEntireSuccess',abcEntireSuccess);

    module.exports = router;

  function abcEntireSuccess(req, res) {

    dashboardService.abcEntireSuccess(req.body)
          .then(function (result) {
          if (result.length > 0) {
            console.log("we get data in node :: " + 
        Object.values(result));
            console.log(result.length + " record found  ");
            res.send(result);
           } 
         else {
            result=[];
            res.send(result);
         }
       })
       .catch(function (err) {
        res.status(400).send(err);
        console.log("some error occured");
       });
       }

Jmeter 板.service.js

var mysql = require('mysql');
    var Q = require('q');
    var express = require('express');
    var service = {};
    var config = require('../../config.json');
    const async = require('async');

       service.abcEntireSuccess = abcEntireSuccess;

        module.exports = service;

 function abcEntireSuccess() {

  var sqlQuery = `select * from TRANSACTION_PAYLOAD where INTERFACE_NAME =  
   'abc' AND (STATUS ='SUCCESS_RESPONSE')`

    var deferred = Q.defer();

    var host = config.host;
    var user = config.user;
    var password = config.password;
    var database = config.database;

     var con = mysql.createConnection({
     host: host,
     user: user,
     password: password,
     database: database
       });

      con.connect(function (err) {
       if (err) deferred.reject(err.name + ': ' + err.message);

       con.query(sqlQuery,
           function (err, result, fields) {
            if (err) deferred.reject(err.name + ': ' + err.message);

            console.log("my result => ",result);

            deferred.resolve(result);

        });

       })

     console.log(" deferred.promise; ");
    return deferred.promise;

  }

请帮助实施。
@船长
更新
当我实现你的代码时。。。我在有Angular 的用户界面(html)中遇到这个错误,
岗位http://localhost:8096/ Jmeter 板/entiresuccess/404(未找到)
请帮助解决

ctrmrzij

ctrmrzij1#

您可以尝试下面的after代码

//dashboard.controller.js
var express = require('express')
var router = express.Router()
var dashboardService = require('./dashboard.service.js');

router.get('/test2',function(req,res){
  console.log(dashboardService.abcEntireSuccess());
});

module.exports = router

//dashboard.service.js
var mysql = require('mysql');
var express = require('express');
var config = require('../config/config.json');
var exports = module.exports = {};

exports.abcEntireSuccess = function() {
    const db = new Database(config);
    db.query( 'SELECT * FROM users' ).then( rows => {
        return rows;
    } );
db.close();
};

class Database {
    constructor( config ) {
        this.connection = mysql.createConnection( config.values);
    }
    query( sql, args ) {
        return new Promise( ( resolve, reject ) => {
            this.connection.query( sql, args, ( err, rows ) => {
                if ( err )
                    return reject( err );
                console.log(rows);
                resolve( rows );
            } );
        } );
    }
    close() {
        return new Promise( ( resolve, reject ) => {
            this.connection.end( err => {
                if ( err )
                    return reject( err );
                resolve();
            } );
        } );
    }
 }
//congfig/config.json
{
    "values" : {
        "host" : "localhost",
        "user" : "root",
        "password" : "",
        "database" : "demo"
    }
}

相关问题