NodeJS MSSQL多次查询承诺

时间:2017-08-09 15:03:20

标签: sql-server node.js promise

使用mssql npm库时遇到很多问题。

这是我的db类:

"use strict"
const mssql = require('mssql');
const moment = require("moment");
let pool_historian = null;
let connexion_historian = null;

function mapBarChart(array) {
    return new Promise((resolve, reject) => {
        let result = {}
        result.old = []
        result.this = []
        let currentYear = null;
        for (let i = 0; i < array.length; i++) {
            if (parseInt(moment().format("YYYY")) !== array[i].Annees) {
                result.old.push(array[i]);
            } else {
                result.this.push(array[i]);
            }
        }
        resolve(result);
    })
};

class Historian {
    constructor(data) {
        pool_historian = new mssql.ConnectionPool({
            server: data.host,
            user: data.username,
            password: data.password,
            database: data.historian_db,
            pool: {
                max: 50,
                min: 1
            }
        });
    }

    getBarChart(sensor, from, to) {
        return pool_historian.connect().then(connector => {
            return connector.query`SELECT Annees=YEAR(DateTime),Mois=MONTH(DateTime), Valeur=ROUND(sum(AnalogHistory.Value),2) FROM AnalogHistory WHERE AnalogHistory.TagName IN (${sensor}) AND Quality = 0 AND wwVersion = 'Latest' AND wwRetrievalMode = 'Full' AND DateTime >= ${from} AND DateTime <= ${to} AND AnalogHistory.Value > 0 GROUP BY YEAR(AnalogHistory.DateTime),MONTH(AnalogHistory.DateTime) ORDER BY Annees, Mois`.then(result => {
                connector.close();
                return mapBarChart(result.recordset).then(result => { return result });
                //return result.recordset;
            }).catch(err => {
                return err;
            })
        })
    }
    getLineChart() {
        return pool_historian.connect().then(connector => {
            let variable = "A_000000000000000000000000000045.PV";
            return connector.query`SELECT Annees=YEAR(DateTime),Mois=MONTH(DateTime),day=DAY(DateTime), Valeur=ROUND(sum(AnalogHistory.Value),2) FROM AnalogHistory WHERE AnalogHistory.TagName IN (${variable}) AND Quality = 0 AND wwVersion = 'Latest' AND wwRetrievalMode = 'Cyclic' AND DateTime >= '20160101 00:00:00.000' AND DateTime <= '20170809 00:00:00.000' AND AnalogHistory.Value > 0 GROUP BY YEAR(AnalogHistory.DateTime),MONTH(AnalogHistory.DateTime), Day(AnalogHistory.DateTime)ORDER BY Annees, Mois`.then(result => {
                connector.close();
                return result.recordset;
            }).catch(err => {
                return err;
            })
        })
    }

    close() {
        pool_historian.close()
    }
}

此类用于此“业务类”:

const Historian = require(`${__dirname}/historian-query`)
const Fdedb = require(`${__dirname}/fdedb-query`)
const moment = require('moment');

moment.locale("fr-FR");

class Graph_Tasks {
    constructor() {
        this.historian = new Historian({ host: "192.168.1.16", username: "******", password: "w***", historian_db: "R******e" })
        this.fdedb = new Fdedb({ host: "192.168.1.16", username: "*****", password: "*****", fde_db: "S*****" })
    }

    createGraphForBuilding(code) {
        return new Promise((resolve, reject) => {
            this.fdedb.getList(code).then(list => {
                console.log(list)
                let datas = [];

                //Foreach item on the list perform these 2 queryes

                Promise.all([this.historian.getLineChart("A_000000000000000000000000000045.PV", moment().subtract(1, "years").startOf("year").format(), moment().format()), this.historian.getBarChart("A_000000000000000000000000000045.PV", moment().subtract(1, "years").startOf("year").format(), moment().format())]).then(results => {
                    let datas = []
                    datas = { "lineChart": null, "barChart": results[0] };
                    console.log(datas)
                    res.render('index', { title: 'WebGraph', message: 'Yo Yo', datas });
                })

                console.log(datas)
                resolve(datas)

            }).catch(console.log);
        });

    }
}
module.exports = Graph_Tasks;

正如您所看到的,我正在尝试执行的是同时执行数据库请求。正如我在文档中看到的那样,连接池必须让我正确地执行此操作。因此,当程序到达Promise.all时,我预计这两个请求将同时启动。

但是我收到了一个错误:

  

Une exception s'est produite:错误
  承诺拒绝(ConnectionError:已经连接到数据库!在连接到不同的数据库之前调用close。)
  ConnectionError:已经连接到数据库了!在连接到不同的数据库之前调用close   在ConnectionError(d:\ repositories \ fde \ node_modules \ mssql \ lib \ base.js:1428:7)
  在ConnectionPool._connect(d:\ repositories \ fde \ node_modules \ mssql \ lib \ base.js:235:23)
  在EventEmitter.connect.PromiseLibrary(d:\ repositories \ fde \ node_modules \ mssql \ lib \ base.js:217:19)
  在ConnectionPool.connect(d:\ repositories \ fde \ node_modules \ mssql \ lib \ base.js:216:12)
  在Historian.getBarChart(d:\ repositories \ fde \ class \ historian-query.js:39:31)
  at __dirname.createGraphForBuilding.Promise.fdedb.getList.then.list(d:\ repositories \ fde \ class \ graph_tasks.js:21:188)
  at process._tickCallback(internal / process / next_tick.js:109:7)

所以我的问题是:如何调整代码让我同时执行多个查询(我的每个列表项的promise.all)?

1 个答案:

答案 0 :(得分:0)

问题是您无法打开到同一服务器的多个连接池(我认为Fdedb正在打开另一个连接,因为您未包含该连接的代码)。例如,如果您要从两个不同的服务器中提取数据,那么打开两个连接池将是合适的-我之前已经遇到过该用例。但是看起来您的两个数据库位于同一服务器(本地主机)上,因此最好只打开一个连接并将其传递给对象以进行查询。您可以使用普通的旧SQL触摸同一主机上的多个数据库,请参阅:How do I query tables located in different database?