javascript - 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 并在数组中获取结果。谢谢你。
解决方案
当您开始遇到许多请求时,通常会出现此问题。您可以在一个数组中获得所有承诺并解决它。你可以使用 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。它很容易实现。
推荐阅读
- laravel-5 - 在 Laravel 中打印
- javascript - Angular 模块应该是一个空的 JavaScript 模块吗?
- android - 使用 Youtube App 等选项列表创建弹出窗口
- html - 如何使 HTML 列表环绕浮动内容
- mysql - 不能写重复键,使用组合主键
- javascript - 如何在页面加载时停止执行某个 javascript
- vb.net - DataGridView 中的复选框。更改选中单元格的 Style.Backcolor
- javascript - 阿贾克斯返回整页
- erlang - 如何在 Erlang/Elixir 5 秒后自定义重启策略?
- c# - Photon PUN 2+ Unity 仅在我在本地运行两个实例时工作