I have question regarding asynchronous functions and how to send something after a function has returned it's result. This is what I am trying to accomplish:
Within the handling of a GET request in Node I read the contents of a folder, returning the files in that folder. Next I want to loop over the stats of each file in that folder, loading only the files created within a certain period and lastly send the data in those files as a response to the request. It looks something like this:
array = []
fs.readdir(path, function(err, items) {
items.forEach(function(item) {
fs.stat(path, function(err, stats) {
if (period check) {
array.push(data)
}
})
})
}
res.send(array)
This approach ends up sending an empty array, and I've looked into Promises which seem the solution here but I can't get them to work in this scenario. Using fs.statSync instead of fs.stat does work but this greatly reduces the performance, and it feels like it should be doable with Promises but I just don't know how.
Is there anyone with a solution for this?
EDIT: Regarding to the question marked as duplicate, I tried to solve my problem with the answer there first but didn't succeed. My problem has some nested functions and loops and is more complex than the examples given there.