使用异步/等待与foreach循环 [英] Using async/await with a forEach loop

查看:412
本文介绍了使用异步/等待与foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有与在的forEach 循环中使用异步/的await 的任何问题?我通过文件的数组试图环和等待上的每个文件的内容。

Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file.

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

这code的工作,但可能的东西去错了呢?我曾有人告诉我说,你不应该使用异步/的await 在这样的高阶函数,所以我只是想问问是否有任何问题与此有关。

This code does work, but could something go wrong with this? I had someone tell me that you're not supposed to use async/await in a higher order function like this so I just wanted to ask if there was any issue with this.

推荐答案

确定code的工作,但我是pretty确保它不会做你希望它做什么。它只是关闭触发多个异步调用,但 printFiles 函数并后立即返回。

Sure the code does work, but I'm pretty sure it doesn't do what you expect it to do. It just fires off multiple asynchronous calls, but the printFiles function does immediately return after that.

如果你想阅读的文件按顺序,您不能使用的forEach 确实如此。只要用现代为... 循环代替,其中等待将如预期的:

If you want to read the files in sequence, you cannot use forEach indeed. Just use a modern for … of loop instead, in which await will work as expected:

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

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

如果你想读的文件并行,您不能使用的forEach 确实如此。每个在的异步的回调函数调用不会返回一个承诺,但你扔掉,而不是等待他们的。只需使用地图相反,你可以等待的承诺,你会用 Promise.all 得到的数组:

If you want to read the files in parallel, you cannot use forEach indeed. Each of the the async callback function calls does return a promise, but you're throwing them away instead of awaiting them. Just use map instead, and you can await the array of promises that you'll get with 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)
  }));
}

这篇关于使用异步/等待与foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆