Categories
JavaScript Answers

How to Fetch an Array of URLs with the Promise.all Method?

Spread the love

To fetch an array of URLs with the Promise.all method, we can call map to map an array of URLs to promises that fetch the data from the URLs.

Then we can call Promise.all on the array of promises.

For instance, we can write:

const fetchAll = async (urls) => {
  const res = await Promise.all(urls.map(u => fetch(u)))
  const jsons = await Promise.all(res.map(r => r.json()))
  console.log(jsons)
}

const urls = [
  'https://yesno.wtf/api',
  'https://yesno.wtf/api',
  'https://yesno.wtf/api'
]
fetchAll(urls)

to create the fetchAll function that takes an array of urls .

Then we call urls.map with a callback that returns promises returned by fetch for the URL u .

Then we call Promise.all on the array to return a promise with an array of response objects and assign it to res .

Next, we call res.map with a callback that return the JSON response object with the r.json method.

And then we call Promise.all on that to return a promise with the response JSON objects.

Therefore, jsons is something like:

[
  {
    "answer": "yes",
    "forced": false,
    "image": "https://yesno.wtf/assets/yes/10-271c872c91cd72c1e38e72d2f8eda676.gif"
  },
  {
    "answer": "yes",
    "forced": false,
    "image": "https://yesno.wtf/assets/yes/11-a23cbde4ae018bbda812d2d8b2b8fc6c.gif"
  },
  {
    "answer": "yes",
    "forced": false,
    "image": "https://yesno.wtf/assets/yes/0-c44a7789d54cbdcad867fb7845ff03ae.gif"
  }
]

since we called with 3 URL strings in the urls array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *