Tengo una situación en la que necesito leer todos los archivos en un directorio y todos sus subdirectorios. Escribí una función básica:
Aunque esto está en React-Native, no estoy seguro de que importe (o tal vez haya una solución de reacción nativa).
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'Esto parece funcionar parcialmente ya que todos los archivos en todos los subdirectorios se consolan desde dentro del segmento else {...}.
Sin embargo, ¿cómo puedo saber que el ciclo está completo para poder continuar con el script y usar 'fileList'?
No use forEach con async , no funcionan juntos y no puede esperar el bucle. Use un estándar for .. of bucle, que funciona bien con 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); } } } Y como readDir es async , por supuesto, también debe await o usarlo para then una vez que haya terminado.
async function foo() { const parentDirectory = "parent_folder"; await readDir(parentDirectory); //do some other stuff once readdir is finished. }o
const parentDirectory = "parent_folder"; readDir(parentDirectory).then(_ => { //do some other stuff once readdir is finished. }