首页 > JavaScript > 如何将 async/await 与 forEach 循环结合使用?

如何将 async/await 与 forEach 循环结合使用?

上一篇 下一篇

在循环中使用 / 有任何问题吗?我正在尝试遍历一系列文件和每个文件的内容。asyncawaitforEachawait

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()

这段代码确实有效,但这会不会出错?我有人告诉我,你不应该在这样的高阶函数中使用 /,所以我只是想问一下这是否有任何问题。asyncawait

分割线

网友回答:

使用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 … ofawait

async function printFiles () {
  const files = await getFilePaths();

  for (const file of files) {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }
}

并行阅读

如果要并行读取文件,则确实不能使用forEach。每个回调函数调用都会返回一个 promise,但您正在丢弃它们而不是等待它们。只需改用,您就可以等待您将获得的一系列承诺:asyncmapPromise.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.allArray.prototype.mapPromiseArray.prototype.reducePromise

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】栏目查找您需要的精美模板。

相关搜索
  • 下载密码 lanrenmb
  • 下载次数 195次
  • 使用软件 Sublime/Dreamweaver/HBuilder
  • 文件格式 编程语言
  • 文件大小 暂无信息
  • 上传时间 03-04
  • 作者 网友投稿
  • 肖像权 人物画像及字体仅供参考
栏目分类 更多 >
热门推荐 更多 >
微信文章 微信素材 微信模板 微信图片 响应式 微信公众平台 企业网站 单页式简历模板 html5 自适应
您可能会喜欢的其他模板