Answer the question
In order to leave comments, you need to log in
How to get data from the module that pulls the database, nodejs / express?
Good afternoon! I beg you to explain!
What to use in this case, so that it is not shitty code and everything works?
Wrote a module that retrieves data from the database. How to get data from the database is clear!
it is not clear how to transfer them further to another module, how can I get a response from this module?
Please explain at least how this is done, in which direction to look?
Ideally, this would be some kind of example.
Thank you!
The module itself
function getDataFromDatabase() {
var arr = []
var con = mysql.createConnection(conf.config);
return con.connect(function (err) {
if(err) throw err;
con.query("SELECT DID, DName FROM Device")
.on('result', function (data) {
arr.push(data)
})
.on('end', function () {
return JSON.stringify(arr)
})
});
}
getDataFromDatabase()
module.exports.getDataFromDatabase = getDataFromDatabase;
Answer the question
In order to leave comments, you need to log in
Can be done with callback
var getDataFromDatabase = function () {
var arr = []
var con = mysql.createConnection(conf.config);
con.connect(function (err) {
if(err) throw err;
con.query("SELECT DID, DName FROM Device")
.on('result', function (data) {
arr.push(data)
})
.on('end', function () {
return callback(null, arr);
})
.on('error', function(err){
return callback (err, null);
});
}
module.exports = {
getDataFromDatabase
}
var fromDB = require(./modulName);
fromDB.getDataFromDatabase(function(err, result){
if(err){
console.log(err);
} else {
console.log(result);
}
})
var getDataFromDatabase = function (callback) {
return new Promise((resolve, reject) => {
var arr = []
var con = mysql.createConnection(conf.config);
con.connect(function (err) {
if (err) throw err;
con.query("SELECT DID, DName FROM Device")
.on('result', function (data) {
arr.push(data)
})
.on('end', function () {
return resolve(arr);
})
.on('error', function (err) {
return reject(err);
})
});
})
}
module.exports = {
getDataFromDatabase
}
var fromDB = require("./modulName");
fromDB.getDataFromDatabase()
.then(result =>{
console.log(result);
},(err)=>{
console.log(err);
})
var getDataFromDatabase = async function (callback) {
return new Promise((resolve, reject) => {
var arr = []
var con = mysql.createConnection(conf.config);
con.connect(function (err) {
if (err) throw err;
con.query("SELECT DID, DName FROM Device")
.on('result', function (data) {
arr.push(data)
})
.on('end', function () {
return callback(null, arr);
})
.on('error', function (err) {
return callback(err, null);
})
});
})
}
module.exports = {
getDataFromDatabase
}
var fromDB = require("./modulName");
var test = await fromDB.getDataFromDatabase();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question