首页 > 解决方案 > Openweathermap 循环遍历城市 id 以获取当前天气

问题描述

我的数据库中有一个城市列表和城市 ID。我想遍历城市并使用 axios 在数组中获取每个城市的当前天气。我试过这个,

const job = schedule.scheduleJob('*/1 * * * *', async () => {
  const cities = await City.find({}, { _id: 0, cityId: 1 });
  const current_weather = [];
  await cities.forEach((city) => {
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?id=${city.cityId}&appid=${process.env.API_KEY}`)
      .then((response) => current_weather.push(response))
      .catch((error) => console.error(error));
  });
  console.log(current_weather);
});

但是每个 Axios 请求都是打印Error: connect ENOBUFS - Local (undefined:undefined)错误。请找到一种解决方案来循环遍历城市 ID 并在数组中获取结果。谢谢你。

标签: javascriptnode.jsasynchronousaxiosopenweathermap

解决方案


当您开始遇到许多请求时,通常会出现此问题。您可以在一个数组中获得所有承诺并解决它。你可以使用 promises.all:

const job = schedule.scheduleJob('*/1 * * * *', async () => {
  const cities = await City.find({}, { _id: 0, cityId: 1 });
  const current_weather = [];
  await cities.forEach((city) => {
    const reqData = axios
      .get(`http://api.openweathermap.org/data/2.5/weather?id=${city.cityId}&appid=${process.env.API_KEY}`)
     current_weather.push(reqData);
  });
   Promises.all(current_weather).then(dataFromApi => {
      // dataFromApi will be an Array and gives the data in same format you called API's for different cities.
   }).catch(e) {
     console.log(`Error is ${e}`);
  }
  console.log(current_weather);
});

如果上述解决方案不起作用,您可以使用throlle-queue lib。它很容易实现。


推荐阅读