在循环中使用 / 有任何问题吗?我正在尝试遍历一系列文件和每个文件的内容。async
await
forEach
await
import fs from 'fs-promise'
async function printFiles () {
const files = await getFilePaths() // Assume this works fine
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
})
}
printFiles()
这段代码确实有效,但这会不会出错?我有人告诉我,你不应该在这样的高阶函数中使用 /,所以我只是想问一下这是否有任何问题。async
await
网友回答:
使用ES2018,您可以大大简化上述所有答案:
async function printFiles () {
const files = await getFilePaths()
for await (const contents of files.map(file => fs.readFile(file, 'utf8'))) {
console.log(contents)
}
}
请参阅规范:提案异步迭代
简化:
for await (const results of array) {
await longRunningTask()
}
console.log('I will wait')
2018-09-10:这个答案最近引起了很多关注,有关异步迭代的更多信息,请参阅Axel Rauschmayer的博客文章。
网友回答:
当然代码确实有效,但我很确定它没有做你期望它做的事情。它只是触发多个异步调用,但函数会在此之后立即返回。printFiles
如果要按顺序读取文件,则确实不能使用每个
文件。只需改用现代循环,它将按预期工作:for … of
await
async function printFiles () {
const files = await getFilePaths();
for (const file of files) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
}
如果要并行读取文件,则确实不能使用forEach
。每个回调函数调用都会返回一个 promise,但您正在丢弃它们而不是等待它们。只需改用,您就可以等待您将获得的一系列承诺:async
map
Promise.all
async function printFiles () {
const files = await getFilePaths();
await Promise.all(files.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}
网友回答:
而不是与(这不能保证解析 s 的顺序)结合使用,我使用 ,以解析的 :Promise.all
Array.prototype.map
Promise
Array.prototype.reduce
Promise
async function printFiles () {
const files = await getFilePaths();
await files.reduce(async (promise, file) => {
// This line will wait for the last async function to finish.
// The first iteration uses an already resolved Promise
// so, it will immediately continue.
await promise;
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}, Promise.resolve());
}
模板简介:该模板名称为【如何将 async/await 与 forEach 循环结合使用?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。