I want to return after collecting all files path but the function return with empty list.
async function gcsFilesListTwo(uid: string): Promise<string[]> {
let ret: string[] = []
if (browser) {
const storage = firestorage();
const listRef = ref(storage, `gs://bucket/folder`);
listAll(listRef)
.then((res) => {
res.prefixes.forEach((folderRef) => {
listAll(folderRef).then(subRes => {
subRes.items.forEach((itemRef) => {
if (itemRef.fullPath.endsWith(".pdf")) {
ret.push(itemRef.fullPath)
}
});
return ret;
// I want to return here after adding all files
//But this happens after the function return
})
});
})
.catch((error) => {
console.log("list error", error)
});
return ret
}
return ret
}
2
Answers
Although the answer is in the comments i am posting the revised code here for a non-TS programmers like me.
What you’re doing right now, you’re mixing
async
withthen/catch
callbacks. It’s one or the other, never both. However, as @DougStevenson also mentioned in his comment, if you want to declare your function as anasync
function, then you have to useawait
to wait for all promises to be resolved so you can get the result of the request. This solution is much simpler than using thethen/catch
callbacks.As I see in your code, you’re using a
forEach
but in the case of asynchronous calls, it will not work for sure as you might expect. So to solve this, you should create an empty array in which you should all promises and in the end simply call:More info below: