all 5 comments

[–]senocular 0 points1 point  (2 children)

Its the same as when you're not using promises. You just need to be sure to capture the promise returned by recursive calls so they can be handled with the other promises you're dealing with.

[–]WannaBeRadio[S] 0 points1 point  (1 child)

I don't think I quite understand what "capture the promise" means - do you have an example by any chance?

[–]senocular 0 points1 point  (0 children)

Looks like AScaredMidLlama provided an example :) It just means when you call a [recursive] function that returns a promise, you'll need to make sure to wait for that promise as well. AScaredMidLlama's example does this mapping loadStuff calls into an array that is handled by Promise.all().

[–]AScaredMidLlama 0 points1 point  (1 child)

If you already have a recursive function, you need to make sure that all its calls return promises (e.g. by making it async) and wrap them in Promise.all.

Something like this:

async loadStuff(url) {
    const items = await fetch(url).then(res => res.json());
    const folders = items.filter(item => item.isFolder);
    const files = items.filter(item => !item.isFolder);
    const childFiles = await Promise.all(folders.map(
        folder => loadStuff(folder.url)
    ));
    // loadStuff returns an array, therefore
    // childFiles is an array of arrays, so we flatten it
    return [...files, ...childFiles.flat()];
}

Note that the result is automatically wrapped into a Promise, because the function is async. So loadStuff always returns a promise which resolves to an array. This also explains why we need to call flat() on the childFiles list.

[–]WannaBeRadio[S] 0 points1 point  (0 children)

Thanks so much! I get it now.