Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过城市id打开天气图循环以获取当前天气_Javascript_Node.js_Asynchronous_Axios_Openweathermap - Fatal编程技术网

Javascript 通过城市id打开天气图循环以获取当前天气

Javascript 通过城市id打开天气图循环以获取当前天气,javascript,node.js,asynchronous,axios,openweathermap,Javascript,Node.js,Asynchronous,Axios,Openweathermap,我的数据库中有一个城市列表和城市id。我想在各个城市中循环,并使用axios在阵列中获取每个城市的当前天气。我试过这个 const job = schedule.scheduleJob('*/1 * * * *', async () => { const cities = await City.find({}, { _id: 0, cityId: 1 }); const current_weather = []; await cities.forEach((city) =>

我的数据库中有一个城市列表和城市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请求都在打印
错误:connect ENOBUFS-Local(未定义:未定义)
错误。请找到一个通过城市id循环的解决方案,并在数组中获得结果。谢谢。

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

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);
});


如果上述解决方案不起作用,可以使用lib。这很容易实现。

要解决此问题,您可以使用库限制队列,请查看此项