Follow by Email

NodeJS Using async/await in a for loop


async/await feature deals with Promises and function chaining. The functions need not to be chained one after another, simply await the function that returns the Promise. But the function async needs to be declared before awaiting a function returning a Promise.
Using Async/await in a for loop, below is the code snippet :



    async function diplayFiles () {
     const files = await getPaths();
     for (const file of files) {
         const filecontents = await fs.readFile(file, 'utf8');
          console.log(filecontents);
        }
    }


NOTE: Async function returns a Promise. If the function throws an error, the Promise will be rejected. If the function returns a value, the Promise will be resolved.