[英]How to use async and await inside a map function for sequential executing
[英]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.