I am working with NodeJS
using express
with this I have the routes such as POST and GET I connect to bd
and make queries in the < strong> app , but I have a question about the following code:
function getAllDatabases() {
return new Promise(function (resolve, reject) {
connection.query("SHOW DATABASES;", function (err, result) {
// console.log(result);
if (err) {
return reject(err);
}
resolve(result);
});
});
}
var data = [];
function getDataConfig(data_array, res) {
console.log(data_array);
return new Promise(function (resolve, reject) {
for (let i = 0; i < data_array.length; i++) {
connection.query("SELECT * FROM " + data_array[i].Database + ".config ", function (err, result) {
if (err) {
return reject(err);
}
resolve(res.json(result));
});
}
});
}
router.post('/add_config', function (req, res) {
var databases = [];
var data = {
Dg: req.body.Dg,
Source: req.body.Source.toLowerCase(),
Label_1: req.body.Label_1,
Label_2: req.body.Label_2,
Label_3: req.body.Label_3,
Styles: req.body.Styles,
Method: req.body.Method,
Intervals: req.body.Intervals,
allow: req.body.Allow,
smart: req.body.Smart,
units: req.body.Units,
resolution: req.body.Resolution
}
getAllDatabases().then(resp => getDataConfig(resp, res));
});
I want to know how to send the res.json (result); that is within the second resolve () in the function getDataConfig
, when I send it of that json
, I get the following error
Error: Can not set headers after they are sent.
the reason I know it because being the res.json
within a loop sends the answer and ends immediately that res.json
works as if it were a return , it gives the value and ends, Is there any way to solve this problem?
thanks