so I'm trying to chaing some SELECT sql queries with tedious promises and can't seem to be able to do so. I get the results I want through the query but it keeps returning undefined.
Here's some of the code:
function getSoma(tableName, cod, index) {
let somaResult;
tp.sql(
`DECLARE @tableName varchar(1000)
SET @tableName = 'SELECT soma from tbs_cod_${tableName} WHERE cod=${cod}'
EXEC (@tableName)`
)
.execute()
.then(async (results) => {
// do something with the results
somaResult = results;
})
.fail(function (err) {
// do something with the failure
console.log("nay" + err);
});
return somaResult;
}
and here's where I call the getSoma function in order to push it to another array, but it keeps showing undefined
let codesSum;
// post para a API para obter o array de código
axios
.post("http://138.68.29.250:8082", qs.stringify(req.body), {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
})
.then((response) => {
codesSum = response.data.split(/[A-Za-z]*#/gi).filter(Boolean);
codesArray.map((element, index) => {
return (element.cod = Number(codesSum[index]));
});
executeStatementMultipleInsert(codesArray);
console.log(codesArray);
})
.then(() => {
codesArray.forEach(async (element, index) => {
console.log(getSoma(Object.keys(element)[0], element.cod, index))
});
})
.then(() => console.log(codesSum))
.catch((err) => console.log(err));
Any clues on how to solve this? I suspected it might have something to do with asynchronicity but I'm kinda stuck.
EDIT 1: by using the await I could get the results from the getSoma function but I can't seem to push the results to another array like in this code
let codesSum;
let soma;
// post para a API para obter o array de código
axios
.post("http://138.68.29.250:8082", qs.stringify(req.body), {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
})
.then((response) => {
codesSum = response.data.split(/[A-Za-z]*#/gi).filter(Boolean);
codesArray.map((element, index) => {
return (element.cod = Number(codesSum[index]));
});
executeStatementMultipleInsert(codesArray);
console.log(codesArray);
codesArray.forEach(async (element) => {
soma = await getSoma(Object.keys(element)[0], element.cod);
console.log(soma);
codesSum.push(soma);
});
console.log(codesSum)
})
.catch((err) => console.log(err));
```