skip to Main Content

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


  1. Chosen as BEST ANSWER

    Although the answer is in the comments i am posting the revised code here for a non-TS programmers like me.

    async function gcsFilesListTwo(uid: string): Promise<string[]> {
        let ret: string[] = []
        if (browser) {
                    const storage = firestorage();
            const listRef = ref(storage, `gs://bucket/folder`);
    
            const res = await listAll(listRef)
            for (const folderRef of res.prefixes) {
                let subRes = await listAll(folderRef)
                for (const itemRef of subRes.items) {
                    if (itemRef.fullPath.endsWith(".pdf")) {
                        ret.push(itemRef.fullPath)
                    }
                }
            }
            return ret
        }
        return ret
    }


  2. What you’re doing right now, you’re mixing async with then/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 an async function, then you have to use await to wait for all promises to be resolved so you can get the result of the request. This solution is much simpler than using the then/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:

    await Promise.all(promises);
    

    More info below:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search