0

I am trying to loop over an array of URLs and go fetch the data at that URL's endpoint then store it as JSON objects in an array (allData). When I run my code and check what's in allData it is continuously an array of nulls. This tells me I'm not returning correctly from the .map? How do I do that given the data is coming from an async function. Here's my code below. Thanks

const allData = urls.map((url)=>{
    fetch(url)
        .then(response => response.json())
        .then((data) => {return data})
        .catch(err => console.log(err))
})   
ByAdham
  • 53
  • 1
  • 5
  • You've got multiple issues going on here, like not returning anything in the map function, but there are already solutions to exactly this problem. I've linked to one of them above, but if you prefer a longer-format blog article then check this out: https://dev.to/nyagarcia/array-map-async-await-2cif – JDB Aug 18 '21 at 20:47
  • Both very helpful. Thank you – ByAdham Aug 18 '21 at 21:03

1 Answers1

1

You need to wait for the promises in the array to be resolved and return the promise in the .map function

const urls = ['https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8', 'https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8']
const allData = urls.map((url)=>{
    return fetch(url)
        .then(response => response.json())
        .then((data) => {return data})
        .catch(err => console.log(err))
})   
Promise.all(allData).then(console.log)

Vincent Menzel
  • 1,040
  • 1
  • 6
  • 17