Solution: Check Your Directory
Exercise solution to "Check Your Directory" where the solution leverages asynchronous programming, promises, and async functions
We'll cover the following...
Solution
For the solution of the exercise, use the file reading function fs.readFile. Wrap it inside a promise to use it inside our async function. In our callback of the fs.readFile function, call resolve function if an error does or does not occurs, and supply it an array with the file name and boolean value. This makes each file name its own promise and uses the Promise.all function to resolve all of them together, along with the await token. See the solution below.
const fs = require('fs'); // import fs module// promise creating function for any file readfunction readFile(filename){ // function to return promisereturn new Promise((resolve,reject) => {fs.readFile(filename,'utf8', (err, data) => {if(err){ // check for errorresolve([filename, false]); // file read unsuccessful} else{resolve([filename, true]); // file read successful}});});}async function finder(filenames){let promiseList = []; // list all promises// populate promiseList with promises for each filenamefilenames.forEach(x => {promiseList.push(readFile(x));});data = await Promise.all(promiseList); // wait to resolve all promisesreturn data;}var ans = finder(['index.js', 'content.txt','funny.txt']);ans.then(val => {console.log(val)});
In the code above, create a general function readFile (lines 3 to 13) which returns a promise for any file name (filename) provided as an argument. The promise returned on line 4 takes an anonymous function which calls resolve function from inside the fs.readFile function’s callback. We have two invocations for the resolve function for the following cases.
errvalue is notnull(line 7): Indicates that the file reading was not successful, and so we provide an array as an argument toresolvefunction withfilenameand the valuefalse.errvalue isnull(line 9): Indicates that the file reading was successful, and so we provide an array as an argument toresolvefunction withfilenameand the valuetrue.
Given that, move onto creating the async function finder with the token async (line 15). First, initialize an empty array for promises and assign it to the promiseList variable (line 16). Then, iterate the filenames array. For each file name, fetch its corresponding promise via readFile function and push it to the array assigned to promiseList variable (line 18). Fetch an array with all returned values from all promises in promiseList array using the Promise.all function. Assign it to the data variable (line 19). Prepend await to it and wait for all promises to resolve before returning the data variable on line 20. The final answer shows the successful implementation.
This concludes the exercise!