我如何在map()循环中返回fetch()

时间:2019-11-06 08:49:23

标签: arrays reactjs api dictionary

我写了一个关于天气的网络应用程序,我使用了weatherbit api,这只是免费的一部分。我想在map()循环中获取()放克。 我有一个具有城市名称和国家名称的对象。 map()使用fetch()返回每个城市名称和国家/地区  我怎样才能做到这一点? map()循环的每一步都有一个问题,我得到一个JSON ..也许在循环中,我有10个JSON ...我如何将所有Json匹配为一个Json? 这是代码。

 const cityName = [
  {
    "id": 1,
    "name": "Ingolstadt",
    "country": "GE",
  },
  {
    "id": 2,
    "name": "Vienna",
    "country": "AT",
  },
  {
    "id": 3,
    "name": "Istanbul",
    "country": "TR",
  },
  {
    "id": 4,
    "name": "London",
    "country": "GB",
  },
  {
    "id": 5,
    "name": "Ankara",
    "country": "TR",
  },
  {
    "id": 6,
    "name": "Paris",
    "country": "FR",
  },
  {
    "id": 7,
    "name": "Barcelona",
    "country": "ES",
  },
  {
    "id": 8,
    "name": "Amsterdam",
    "country": "NL",
  },
  {
    "id": 9,
    "name": "Belgrade",
    "country": "RS",
  },
  {
    "id": 10,
    "name": "Munich",
    "country": "GE",
  }
]

//should return all city which are in object
 
const citySource = cityName.map((name , country) => {
// get api from weatherbit api , but i dont know ${name} and ${country} right sycntax
    fetch(`https://api.weatherbit.io/v2.0/current?city=${name}&country=${country}&key=86e622607fbe4c2cb9f7f71889a4d48d`)
       .then(response => response.json())
       .then( users => console.log(users));
})    

1 个答案:

答案 0 :(得分:0)

根据MDN

  

map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

这里有一个有效的示例:

const cityName = [
  {
    "id": 1,
    "name": "Ingolstadt",
    "country": "GE",
  },
  {
    "id": 2,
    "name": "Vienna",
    "country": "AT",
  },
  {
    "id": 3,
    "name": "Istanbul",
    "country": "TR",
  },
  {
    "id": 4,
    "name": "London",
    "country": "GB",
  },
  {
    "id": 5,
    "name": "Ankara",
    "country": "TR",
  },
  {
    "id": 6,
    "name": "Paris",
    "country": "FR",
  },
  {
    "id": 7,
    "name": "Barcelona",
    "country": "ES",
  },
  {
    "id": 8,
    "name": "Amsterdam",
    "country": "NL",
  },
  {
    "id": 9,
    "name": "Belgrade",
    "country": "RS",
  },
  {
    "id": 10,
    "name": "Munich",
    "country": "GE",
  }
]

//should return all city which are in object
 
const citySource = cityName.map((city) => {
    fetch(`https://api.weatherbit.io/v2.0/current?city=${city.name}&country=${city.country}&key=86e622607fbe4c2cb9f7f71889a4d48d`)
       .then(response => response.json())
       .then( users => console.log(users));
})