I'm reading a list of filenames from items in a MongoDB server and then checking if any of those filenames exist on local storage. I'm trying to create a list of all the matching filenames, the ones that exist both locally and in the database, and then send that list in an Express response.
Here's what I've come up with.
app.get('/api/album', (req, res) => {
let matches = [];
Album.find({}).then(albums => {
albums.forEach( (item, index) => {
fs.readdir('./static/img/album-art/', (err, files) => {
files.forEach(file => {
if (file !== undefined && item.coverUrl !== undefined) {
if (file == item.coverUrl) {
matches.push(item.name);
}
}
});
});
});
});
res.json(matches);
});
However, the response only contains an empty list because fs.readdir()
is asynchronous. I'd like to keep it asynchronous, but I'm trying to find a way to send the response after it's complete. I'm not great with promises, and I know I can use async/await
here but I haven't been able to get it to work.