I want to use async-await for fs.access
and fs.unlink
. Both the function returns an error without result callback. so the problem is if the function throws error it directly goes to catch block and continue for next iteration.
const unlink = util.promisify(fs.unlink);
const access = util.promisify(fs.access);
const deleteAssetsCtrl = async (req, res) => {
try {
let iteration = 0;
for (let file of fileUrls) {
const fileUrl = file.fileUrl
const fileLocation = path.resolve(contentFolderPath, fileUrl);
access(fileLocation); // step 1
unlink(fileLocation); // step 2
const deleteRowQuery = `DELETE FROM table WHERE fileUrl = '${fileUrl}'`;
executeQuery(deleteRowQuery); // step 3
if (fileUrls.length == iteration){
res.send("true");
} else {
res.send('false')
}
} catch (error) {
console.log('Error =>', error);
res.send(error);
}
}
Error => Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How to control flow. (steps should be in sequence)