I am currently facing a challenge with my post route, where I receive an array of strings from req.body. This array is then used to query my local MySQL database multiple times in order to retrieve specific data that I need to send back to the client (react) and store in state.
The issue arises when trying to store this data in an array to be sent successfully via the res.send or res.json method.
I suspect that the problem might be related to handling scope in a different way, but I am at a loss on how to solve it.
I have attempted to move the declaration of the original array variable around, but even with res.send(aisleArr)
, I only end up receiving an empty array.
I also tried omitting the declaration of 'aisleArr' before using the push method, hoping it would create a global aisleArr object, but that did not work either.
router.post('/complete', (req, res) => {
const list = req.body;
let aisleArr = [];
list.map(item =>
db.item.findAll({
where: {'$item.name$': item}
})
.then(data => data.map( data =>
db.aisle.findAll({
where: {'$aisle.id$': data.dataValues.aisleId, '$aisle.storeId$': 2}
}).then( result => {
if(result[0]){
aisleArr.push(result[0].name)
}else{
console.log('no match')}})
)
)
)
res.send(aisleArr)
});
Upon completion of res.send, the client console only shows an empty array being received.