代码之家  ›  专栏  ›  技术社区  ›  Josh Smith

在预期的异步生命周期Gatsby之外调用了Action createPage

  •  0
  • Josh Smith  · 技术社区  · 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
  •  2
  •   yeah22    5 年前

    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
  •   Jellow    5 年前

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

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

    见规范: proposal-async-iteration


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

        3
  •  0
  •   Johnz    5 年前

    Promise.all 结合 Array.prototype.map Promise Array.prototype.reduce ,从已解决的 承诺 :

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