如何使用await/async替代以下的"then"(map函数)?

3
以下代码接收一堆文件路径,读取这些文件,然后计算它们的单词数量:
;(async () => 
  const wordCounts = await Promise.all(
    filePaths.map(
      filePath => fs.promises.readFile(filePath, 'utf-8')
        .then(fileText => nlp(fileText).wordCount())
    )
  )
})()

如何使用async/await代替在末尾使用then?

1个回答

3

您可以将 .map 回调设置为异步,以便您可以 await 调用 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函数调用时会返回一个Promise对象,该对象会解析到async函数内部返回的值,因此将回调函数设为async函数是可行的,因为它会被传递给Promise.all

谢谢。括号和返回值让一切变得更加清晰。 - alexchenco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接