Javascript 通过城市id打开天气图循环以获取当前天气
我的数据库中有一个城市列表和城市id。我想在各个城市中循环,并使用axios在阵列中获取每个城市的当前天气。我试过这个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) =>
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。这很容易实现。要解决此问题,您可以使用库限制队列,请查看此项