I am running Asynchronous code with a foreach loop, but I need one step to be executed after the entire foreach is completed.
I've read many threads about this but I just can't seem to wrap my head around it to know what to do here.
For example, there is a lot of good information here:
Using async/await with a forEach loop.
I am also not experienced with promises.
const fs = require('fs')
const path = require('path')
let sourceDir = 'srcDir/'
let destDir = 'D:/path/to/destDir/'
const isDirectory = source => fs.lstatSync(source).isDirectory()
const isFile = source => fs.lstatSync(source).isFile()
const getDirectories = source =>
fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory)
const getFiles = source =>
fs.readdirSync(source).map(name => path.join(source, name)).filter(isFile)
const getData_File = file => file.substr(0,3)
getDirectories(sourceDir).forEach(dir => {
let dirName = path.basename(dir)
let newData = []
getFiles(dir).forEach(file => {
setTimeout(() => {
newData.push(getData_File(dirName))
console.log(file)
}, 1000)
})
// If this would run after the above foreach loop, it will contain all data
// However, it is in fact being run immediately and is therefore an empty array
console.log(newData)
})
As described in the code above, I need the last line to run once for each directory after the entire foreach on files is completed. What is the best way to accomplish this?