Reputation: 129
I got the following nodejs code snippet working. It hangs in the end and does n ot return. In the end I want to get, insert and delete users based on the status. If the function does not return I cannot do so. I just gives this output.
[ { UserName: 'user4',
LoggedStatus: 'avail',
UserPass: 'demo',
UserType: 'gen' },
{ UserName: 'user3',
LoggedStatus: 'avail',
UserPass: 'demo',
UserType: 'gen' },
{ UserName: 'user2',
LoggedStatus: 'avail',
UserPass: 'demo',
UserType: 'gen' },
{ UserName: 'user1',
LoggedStatus: 'used',
UserPass: 'demo',
UserType: 'gen' } ]
......(hangs here)....
A) How to get the function getAllRecords() to return and the program to end?? B) Return particular rows or particular values from the DB.
var fs = require("fs");
var sql = require("mssql");
var config = {
"server": "localhost",
"user": "xxxx",
"password": "xxxx",
"database": "dbTA",
"port": 1433
};
function getAllRecords(config) {
sql.connect(config).then(function() {
// Query
new sql.Request().query('select * from USERSTATUS').then(function(recordset) {
console.log(recordset);
}).catch(function(err) {
console.log("Error1", err);
});
}).catch(function(err) {
console.log("Error2", err);
});
}
getAllRecords(config);
Upvotes: 0
Views: 2736
Reputation: 3540
Since you are not closing your DB connection, that active connection is preventing node from ending.
You should close your DB connection in your then
and catch
blocks using sql.close()
Upvotes: 1
Reputation: 156
Promises are unwrapped using .then()
, and anything returned in .then()
will be wrapped in a Promise, allowing you to chain them together.
Let's add some returns and get the value out of your query.
var config = {
"server": "localhost",
"user": "xxxx",
"password": "xxxx",
"database": "dbTA",
"port": 1433
};
function getAllRecords(configuration) {
// return the entire chain of promises
return sql.connect(configuration)
.then(function() {
// return this query so we can have access to its value
return new sql.Request().query('select * from USERSTATUS');
.catch(function(err) {
console.log("Error1", err);
});
}).catch(function(err) {
console.log("Error2", err);
});
}
// since we're returning a promise we have to consume it using a `.then()`
getAllRecords(config).then(function(value) {
console.log(value);
});
Upvotes: 1