In my code, I want to compare arrays and delete files on the server that do not match in arrays. Since unlink is an asynchronous operation, I decided to use the async await. But I'm not sure if I did everything right. Do I need to wrap everything in the Promise.all or remove it altogether
oldFiles.map(async (oldFile) => {
await Promise.all(
editedFiles.map(async (editedFile, index) => {
if (oldFile === editedFile) {
return;
}
//delete file if it the last editedFile that has no overlap with oldFile
if (index === editedFiles.length - 1) {
await unlink(`${filesDir}/${oldFile}`);
}
})
);
});
CodePudding user response:
I feel like a better solution would be to filter oldFiles
for any editedFiles
then create an array of unlink promises to wait on
const editedFilesHash = new Set(editedFiles); // makes for faster lookups
await Promise.all(
oldFiles
.filter((oldFile) => !editedFilesHash.has(oldFile))
.map((oldFile) => unlink(`${filesDir}/${oldFile}`))
);
It was totally unclear what the last index check was for and it seemed completely unnecessary to the overall logic.