How to loop over an array of objects and fetch network data for each one in JS?

Clash Royale CLAN TAG#URR8PPPHow to loop over an array of objects and fetch network data for each one in JS?
I am making apps in React Native. I have to fetch an array of data of categories from a URL and then for each category I have to fetch assets from their respective URLs. This is how far I have gotten:
var result = fetch(url)
.then((response) => response.json())
.then((jsonData) => {
for (var i = 0; i < jsonData.result.length; i++) {
var url = jsonData.result[i];
if (url.name == 'navigationURL') {
return fetch(url.value);
}
}
})
.then((response) => response.json())
.then((jsonData) => {
let categories = ;
for (var i = 0; i < jsonData.subCategories.length; i++) {
var cat = jsonData.subCategories[i];
console.log(Category);
var category = new Category(cat.id, cat.name, cat.type, cat.url, );
console.log(category);
categories.push(category);
}
return categories;
})
How do I fetch data for each category?
.map()
1 Answer
1
You can use Promise.all to make sure that each fetch is complete before you run the next then function in the chain.
Promise.all
fetch
then
Example
var result = fetch(url)
.then(response => response.json())
.then(jsonData => {
return Promise.all(
jsonData.result.map(url => {
if (url.name == "navigationURL") {
return fetch(url.value).then(res => res.json());
}
});
);
})
.then(jsonData => {
let categories = ;
for (var i = 0; i < jsonData.subCategories.length; i++) {
var cat = jsonData.subCategories[i];
console.log(Category);
var category = new Category(cat.id, cat.name, cat.type, cat.url, );
console.log(category);
categories.push(category);
}
return categories;
});
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
better use
.map()– Mohhamad Hasham
1 min ago