How would you optimizely loop through the items
and nestedItems
of each item
? The target is to download and store images and PDFs in file system to make them available without internet connection.
Let's assume I have the following data structure:
const items = [
{
link: 'example.com/image1.png',
nestedItems: [
{
nestedItemLink: 'example.com/pdf11.pdf',
},
{
nestedItemLink: 'example.com/pdf12.pdf',
},
]
},
{
link: 'example.com/image2.png',
nestedItems: [
{
nestedItemLink: 'example.com/pdf21.pdf',
},
{
nestedItemLink: 'example.com/pdf22.pdf',
},
]
}
]
How I loop through the higher order array:
const promises = items.map(async (item) => {
if (!item.link) {
return item;
}
const {
uri
} = await FileSystem.downloadAsync(
item.link,
`${FileSystem.documentDirectory}${item.link
.split('/')
.pop()}`,
);
item.link = uri;
return item;
})
const data = await Promise.all(promises);
There's a few things to consider:
async function downloadItemLinks() {
if (!item.link) {
return item;
}
const {
uri
} = await FileSystem.downloadAsync(
item.link,
`${FileSystem.documentDirectory}${item.link
.split('/')
.pop()}`,
);
item.link = uri;
if (!item.nestedItems || !item.nestedItems.length) {
return item;
}
// This will download all nested items serially
for (const nested of item.nestedItems) {
await <your download promise>
}
return item;
}
// This will download all links in parallel, but for each link its nested links will be downloaded serially. Depending on the volume of links, the concurrency may still be too high
const promises = items.map(async (item) => {
return await downloadItemLinks(item);
});
const data = Promise.allSettled(promises);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.