繁体   English   中英

如何打开下面的“then”并使用await/async代替(map函数)?

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

以下代码采用一堆文件路径,读取文件,然后计算它们的字数:

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

如何使用async/await的而不是then在结束了吗?

您可以使.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();
    })
  )
})()

异步函数在调用时返回 Promises,它解析为异步函数内部返回的值,因此回调是异步的就好了,因为它被传递给Promise.all

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM