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.
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!
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?
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>>)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.