Like @Bergi's response, but with one difference.
Promise.all
rejects all promises if one gets rejected.
So, use a recursion.
const printFiles async = () => {
const files = await getFilePaths();
const readFilesQueue = async (files, index = 0) {
const contents = await fs.readFile(files[index], 'utf8')
console.log(contents)
return files.length <= index
? readFilesQueue(files, ++index)
: files
}
await readFilesQueue(files)
}
printFiles()
PS
readFilesQueue
is inside printFiles
cause the side effect introduced by console.log
, so, it's not cool to have a function that returns the content.
Therefore, the code can simply be designed by that: three separated functions that are "pure" and introduce no side effects, process the entire list and can easily be modified to handle failed cases.
const files = await getFilesPath()
const printFile = async (file) => {
const content = await fs.readFile(file, 'utf8')
console.log(content)
}
const readFiles = async = (files, index = 0) => {
await printFile(files[index])
return files.lengh <= index
? readFiles(files, ++index)
: files
}
readFiles(files)
Future edit/current state
Node supports top-level await (this doesn't have a plugin yet, won't have and can be enabled via harmony flags), it's cool but doesn't solve one problem (strategically I work only on LTS versions). How to get the files?
Using composition. Given the code, causes to me a sensation that this is inside a module, so, should have a function to do it. If not, you should use an IIFE to wrap the role code into an async function creating simple module that's do all for you, or you can go with the right way, there is, composition.
// more complex version with IIFE to a single module
(async (files) => readFiles(await files())(getFilesPath)
Note that the name of variable changes due to semantics. You pass a functor (a function that can be invoked by another function) and recieves a pointer on memory that contains the initial block of logic of the application.
But, if's not a module and you need to export the logic?
Wrap the functions in ana async function.
export const readFilesQueue = async () => {
// ... to code goes here
}
Or change the names of variables, whatever...