How to turn the following "then" and use await/async instead (map function)?

Viewed 36

The following code takes a bunch of file paths, reads the files, then counts their words:

;(async () => 
  const wordCounts = await Promise.all(
    filePaths.map(
      filePath => fs.promises.readFile(filePath, 'utf-8')
        .then(fileText => nlp(fileText).wordCount())
    )
  )
})()

How to use async/await instead of that then at the end?

1 Answers

You can make the .map callback async so you can await the call of readFile:

;(async () => {
  const wordCounts = await Promise.all(
    filePaths.map(async (filePath) => {
      const fileText = await fs.promises.readFile(filePath, 'utf-8');
      return nlp(fileText).wordCount();
    })
  )
})()

Async functions, when called, return Promises which resolve to the value returned inside the async function, so having the callback be async is just fine, since it's being passed to Promise.all.

Related