0

I have connected my sql server database to my nodejs application like this :

DAO.js

const sql = require('mssql')

class DAO {
    constructor() {
        this.sqlConfig = {user: 'connexionMartin', password: 'InfoMartin', server: '192.168.102.232\\SQLEXPRESS', database: 'PROFACE'}
    }

    async connect() {
        try {
            console.log("Connecting database.....");
            let pool = await sql.connect(this.sqlConfig);
            if (pool)
                console.log("Database connected");
        } catch (err) {
            console.log(err);
        }
    }

    async getDataLastHour() {
        try {
            let result = await sql.query('SELECT * FROM PROFACE.dbo.SuiviProduction WHERE Time_Stamp >= DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()),0) AND DATEPART(HOUR,Time_Stamp) = DATEPART(HOUR,GETDATE())-1');
            console.dir(result);
        } catch (err) {
            console.log(err);
        }
    }
}

app.js

const Server = require('./server/Server');
const DAO = require('./server/DAO');
const express = require('express');

const server = new Server();
const dao = new DAO();

server.start();
dao.connect();

Now I want to request my database using dao.getDataLastHour() in app.js, but the function is executed before application is connected to database. I have tried to fix this problem by using promise, like this :

const promise = dao.connect();
promise.then(dao.getDataLastHour());

But it doesn't seem to work.

Perhaps I don't use Promise correctly.

MissKnacki
  • 269
  • 4
  • 15
  • 1
    `connect()` method does not return a `Promise` – ronen Nov 21 '19 at 12:51
  • If you are using await, then you dont have to use then. In this case if sql.connect is returing a promise, you can either return that promise and use then to execute the callback or call connect with await and just return. – Arun Selin Nov 21 '19 at 12:53
  • Can you check if the database connection is successful? – Arun Selin Nov 21 '19 at 12:55
  • @Arun Selin I am using await but dao.getDataLastHour() is executed before database is connected ... – MissKnacki Nov 21 '19 at 12:56
  • @Arun Selin yes connection is successful! – MissKnacki Nov 21 '19 at 13:00
  • In this case, can you make sure if the sql.connect function return a promise or not. One other thing that can be done is sql.connect(config, function(err) { <>}); – Arun Selin Nov 21 '19 at 13:02

3 Answers3

0

To use a then in you function,it need to return any result and turn it in a promise, or not use await, might it will work!

    async connect() {

            console.log("Connecting database.....");
            sql.connect(this.sqlConfig).then(pool => {
              if (pool)
                console.log("Database connected");
            }).catch (err{ 
            console.log(err);
        });
    }

sorry for the bad identification!

Lincoln Teixeira
  • 145
  • 2
  • 10
0

Your method : dao.connect() does not return a promise. So the first thing would be to change that method to return a promise which you can then listen to then decide whether to run a query or not. :

...
connect() {
     return new Promise((resolve, reject) => {
        try {
            console.log("Connecting database.....");
            let pool = sql.connect(this.sqlConfig);
            if (pool)
                console.log("Database connected");
                resolve("Success");
        } catch (err) {
            console.log(err);
            reject(err);
        }
     });
}
...

And then call your connect method like this:

dao.connect().then(
    success => { ... }, // you can continue querying 
    error => { ... } // something went wrong
);

Also try to read a bit about how to use promises here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Differences between promise and async: What is the difference between JavaScript promises and async await?

Node_Ninja
  • 425
  • 2
  • 7
  • 18
0

You can try something like this:

connect() {
 return new Promise((resolve, reject) => {

        let pool = sql.connect(this.sqlConfig, function(err) {
            if(!err) {
                resolve();
            }
            else {
                reject();
            }
        });
 });
}
 dao.connect().then(<<call function here>>)
Arun Selin
  • 603
  • 4
  • 11