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

如何确定Javascript自引用循环是否完成[重复]

  •  0
  • John  · 技术社区  · 1 年前

    我需要读取一个目录及其所有子目录中的所有文件。我写了一个基本函数:

    let fileList = [];
    
    const readDir = async (dir) => {
    
      // This line simply reads the contents of a directory, creating an array of strings
      // of all the files and directories inside 'dir'.
      const items = await FileSystem.readDirectoryAsync(dir); 
    
      items.forEach(async (item) => {
        const f = await FileSystem.getInfoAsync(item); // Gets basic information about the item
        if (f.isDirectory === true) {
          readDir(f.uri); // f.uri is the location of the new directory to read
        } else {
          // runs if the item is a file
          console.log("f.uri: ", f.uri);
          fileList.push(f.uri); // A global variable
        }
      })
    };
    
    const parentDirectory = "parent_folder";
    readDir(parentDirectory);
    
    // Do more stuff here once all files have been read and added to 'fileList'
    
    

    这似乎部分起作用,因为所有子目录中的所有文件都是从else{…}内部调出的段

    但是,我如何知道循环已完成,以便可以继续脚本并使用“文件列表”?

    1 回复  |  直到 1 年前
        1
  •  1
  •   derpirscher    1 年前

    不要使用 forEach 具有 async 它们不能一起工作,你不能等待循环。使用标准 for .. of 循环,与 async/await

    const readDir = async (dir) => {
      const items = await FileSystem.readDirectoryAsync(dir);
    
      for (let item of items) {
        const f = await FileSystem.getInfoAsync(item); 
        if (f.isDirectory === true) {
          await readDir(f.uri); 
        } else {
          console.log("f.uri: ", f.uri);
          fileList.push(f.uri); 
        }
      }
    }
    

    readDir 异步 当然,你也必须 await then

    async function foo() {
       const parentDirectory = "parent_folder";
       await readDir(parentDirectory);
       //do some other stuff once readdir is finished.
    }
    

    const parentDirectory = "parent_folder";
    readDir(parentDirectory).then(_ => {
       //do some other stuff once readdir is finished.
    
    }