The specific problem I encountered was as follows. I have a list of json files in a directory each describe details of a fish with id, images, name, etc.
/fish1.json
/fish2.json
…
I want to process all these files and write to a summary file like this:
/fishes.json
Due to the async nature of Node.js, simply using fs.readFile would result in all files processed asynchronously. How can we know when all the reading has completed so we can start processing the results? For processing a single file, one could use callback function in javascript to achieve this easily, but for multiple files, it is not a good style as pointed out by this stackoverflow answer. As suggested by this answer, one could either use sync versions of fs functions or Promises. Using sync versions of fs functions would block each file reading and possibly result in slow reading if you have a large number of files. Here I present the code snippet for using Promises to solve this problem.