代码之家  ›  专栏  ›  技术社区  ›  parth

如何同步生成js节点中的文件?[副本]

  •  0
  • parth  · 技术社区  · 6 年前

    使用有什么问题吗 async / await 在一个 forEach 循环?我试着在一系列文件中循环 等待 每个文件的内容。

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

    这个代码确实有效,但是它会出问题吗?有人告诉我你不能用 异步 / 等待

    0 回复  |  直到 5 年前
        1
  •  0
  •   Adam Zerner    4 年前

    当然,代码确实可以工作,但我很肯定它没有达到您期望的效果。它只是触发多个异步调用,但是 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 回调函数调用确实返回了一个承诺,但您将它们丢弃而不是等待它们。只是使用 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)
      }));
    }
    
        2
  •  -1
  •   Wojciech Maj    4 年前

    使用ES2018,您可以大大简化以上所有答案:

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

    见规范: proposal-async-iteration


    2018-09-10:这个答案最近备受关注,关于异步迭代的更多信息,请参见Axel Rauschmayer的博客: ES2018: asynchronous iteration