I've been facing a persistent issue that has been troubling me for quite some time now. The setup involves a database in MariaDB (using WAMP) and an API in ExpressJS. Within the database, there are two tables: "menu" and "item," with a foreign key relationship on the menu.
My goal is to update all items and set the foreign key field to null before deleting the menu. However, the update process is not completing quickly enough, causing complications when trying to delete the menu concurrently.
I attempted solutions using Promise and async/await, but neither approach provided sufficient wait times. Any suggestions or ideas on how to resolve this issue?
Here is my code snippet without async/await:
(router.delete('/delete/:menuId', function (req, res, next) {
return Item.findAll({
where: {
menuId: req.params.menuId,
},
})
.then(
itemsFounded => {
//Unlink items / menu
itemsFounded.forEach(element => {
element.update({
menuId: null
})
});
//Then destroy menu
Menu.destroy({
where: {
id: menuId
}
}).then(() => {
return res.status(200);
}).catch((err) => {
console.log(err);
return res.status(400);
})
}
)
.catch((error) => {
console.log(error);
res.status(400).send(error)
});
});)
And here is the code with async/await implementation:
(router.delete('/delete/:menuId', async function (req, res, next) {
return Item.findAll({
where: {
menuId: req.params.menuId,
},
})
.then(
async itemsFounded => {
//Unlink items / menu
const result = await getResult(itemsFounded, req.params.menuId);
if (result === true) {
console.log("Result is true")
return res.status(200);
} else {
console.log("Result is false")
return res.status(400).send("error");
}
}
)
.catch((error) => {
console.log(error);
res.status(400).send(error)
});
});
async function getResult(itemsFounded, menuId) {
console.log("In getResult");
const result = await destroyMenu(itemsFounded, menuId);
console.log("Result of destroyMenu : " + result);
return result;
}
... [Similar structure for other async functions]
The console output will display detailed log information about the execution process and any errors encountered.