Firebase Storage listAll执行顺序问题:收集路径后返回空列表
解决GCS文件列表异步返回空数组的问题
原代码的核心问题是异步操作的执行顺序没处理对:listAll是异步任务,你用.then回调处理结果,但函数本身在回调还没执行完的时候就直接返回了初始的空ret数组,自然拿不到数据。
用async/await重构代码就能解决这个问题,它能让异步代码按预期的顺序执行,确保所有文件路径收集完成后再返回结果:
async function gcsFilesListTwo(uid: string): Promise<string[]> { let ret: string[] = []; if (browser) { const storage = firestorage(); const listRef = ref(storage, `gs://bucket/folder`); try { // 等待第一层文件夹列表加载完成 const res = await listAll(listRef); // 并行处理所有子文件夹,确保所有异步操作都完成 await Promise.all(res.prefixes.map(async (folderRef) => { const subRes = await listAll(folderRef); // 筛选PDF文件路径并批量加入结果数组 const pdfPaths = subRes.items .map(itemRef => itemRef.fullPath) .filter(path => path.endsWith(".pdf")); ret.push(...pdfPaths); })); } catch (error) { console.log("list error", error); } } return ret; }
关键改动说明:
- 用
await listAll(...)替代.then回调,让代码按顺序执行,等异步任务完成后再继续后续逻辑 - 把
res.prefixes.forEach改成Promise.all(res.prefixes.map(...)):forEach不支持异步函数,Promise.all会等待所有子文件夹的listAll操作完成,避免遗漏数据 - 用
try/catch统一处理错误,和async/await的写法更适配
内容的提问来源于stack exchange,提问作者ZAky
相关产品推荐
相关产品推荐

