I am trying to fetch an array of urls and I am confused on why Im getting returned empty objects.
What I am trying to do is to make a function that will send requests to each of the urls in the array and populate a results array.
I use the map method the call a fetch function, in that fetch function I return the data from the response.
Here is my code
let fetchURLS = function(urls){
let result = urls.map( item => {
let x = fetchFunc(item);
console.log("Fetch Returned", x);
return x;
});
console.log("FINAL: ",result)
return result;
}
let fetchFunc = (url) => {
return fetch(url)
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then(data => data)
.catch((error) => {
console.log('Invalid URL');
return 'Invalid URL';
});
}
urls = ["https://fakestoreapi.com/products/categories", "https://fakestoreapi.com/products/1"];
let out_ = fetchURLS(urls);
The output is
"Fetch Returned" // [object Promise]
{}
?
"Fetch Returned" // [object Promise]
{}
"FINAL: " // [object Array] (2)
[// [object Promise]
{},// [object Promise]
{}]