korri
korri

Reputation: 37

Javascript: Multiple fetches in a promise.all

How would I get the city name, into the responses.map in the following code? I'd like to put the city name in each response.

        let cities = ([
        ["Baker City",88,147],
        ["Boise",131,83],
        ["Burns",41,99],
        ["Fairfield",176,64],
        ["Idaho City",146,93],
        ["Jerome",185,35],
        ["McCall",145,143],
        ["Mountain Home",140,57],
        ["Ontario",109,107],
        ["Twin Falls",182,24]
    ])

    Promise.all(cities.map(element => fetch(`https://api.weather.gov/gridpoints/BOI/${element[1]},${element[2]}`)))
        .then(responses => Promise.all(responses.map(res => res.json())))
        .then(text => console.log(text))
        .catch(error => console.log(error))

Upvotes: 0

Views: 44

Answers (2)

let cities = ([
        ["Baker City",88,147],
        ["Boise",131,83],
        ["Burns",41,99],
        ["Fairfield",176,64],
        ["Idaho City",146,93],
        ["Jerome",185,35],
        ["McCall",145,143],
        ["Mountain Home",140,57],
        ["Ontario",109,107],
        ["Twin Falls",182,24]
    ])

    Promise.all(cities.map(element => fetch(`https://api.weather.gov/gridpoints/BOI/${element[1]},${element[2]}`)))
        .then(responses => Promise.all(responses.map(res => res.json())))
        .then(whethers => whethers.map((whether, index) => ({
           ...whether,
           city: cities[index]
        })))
        .then(text => console.log(text))
        .catch(error => console.log(error))

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371168

In the initial cities.map, call .json() on the fetch call, and call .then again, returning both the result of the .json() call and the subarray item you want:

let cities = ([
  ["Baker City", 88, 147],
  ["Boise", 131, 83],
  ["Burns", 41, 99],
  ["Fairfield", 176, 64],
  ["Idaho City", 146, 93],
  ["Jerome", 185, 35],
  ["McCall", 145, 143],
  ["Mountain Home", 140, 57],
  ["Ontario", 109, 107],
  ["Twin Falls", 182, 24]
])

Promise.all(cities.map(subarr => (
  fetch(`https://api.weather.gov/gridpoints/BOI/${subarr[1]},${subarr[2]}`)
    .then(res => res.json())
    .then(result => [result, subarr[0]]) // <-------------------
  )))
  .then(console.log)
  .catch(console.error);

Upvotes: 3

Related Questions