javascript - 将 async/await 与 forEach 循环一起使用

标签 javascript node.js promise async-await ecmascript-2017

forEach 循环中使用 async/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,所以我只想问问是否有任何问题有了这个。

最佳答案

确定代码确实有效,但我很确定它没有按照您的预期进行。它只是触发多个异步调用,但 printFiles 函数会在之后立即返回。

按顺序阅读

如果要按顺序读取文件,确实不能使用forEach。只需使用现代的 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。每个 async 回调函数调用都会返回一个 promise,但您将它们丢弃而不是等待它们。只需使用 map 代替,您就可以 await 通过 Promise.all 获得的 promise 数组:

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

  await Promise.all(files.map(async (file) => {
    const contents = await fs.readFile(file, 'utf8')
    console.log(contents)
  }));
}

关于javascript - 将 async/await 与 forEach 循环一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58085871/

相关文章:

javascript - 什么是 Node 子进程?

javascript - 循环内的 Ajax 调用需要顺序响应

javascript - innerHTML 内的 html 标签

javascript - 在 React Native 中触摸 TextInput 时打开键盘和/或 DatePickerIOS

javascript - JavaScript 中的两种数据绑定(bind)方式

node.js - node.js 中的 TCP 聊天服务器架构......在数据库或内存中保存套接字?

node.js - 使用 PayPal-node-SDK(PayPal Express Checkout)支付授权和获取支付( future )

Node.js - 使用 Promise.all() 加载并执行多个函数

javascript - 调用一个包含来自另一个函数的 Promise 的函数

javascript - 跨域脚本标签适用于 FF 和 Chrome,但不适用于 IE