loksvem
loksvem

Reputation: 33

How can i fetch array of nested arrays sequentially?

I have two nested arrays that contain urls, for example:

[['http://ex.com/1','http://ex.com/2'],['http://ex.com/3']]

How can i fetch urls from the first array simultaneously and fetch url from the second array after resolving the first array ?

Upvotes: 1

Views: 119

Answers (1)

Kasper Seweryn
Kasper Seweryn

Reputation: 366

You can use Promise.all() to fetch couple of urls at once.

async function getResponses (arr) {
  const res = []
  for (const urls of arr) {
    // Fetch all urls at once
    const responses = await Promise.all(urls.map(url => fetch(url)))
    res.push(await Promise.all(responses.map(response => response.text())))
  }

  return res
}

If your responses are in JSON then you can use

responses.map(response => response.json())

Upvotes: 1

Related Questions