0

I have a list of cities and the city id in my database. I want to loop through the cities and get the current weather of each city in an array using axios. I tried this,

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

But each Axios request is printing Error: connect ENOBUFS - Local (undefined:undefined) error. Please find a solution to loop through city id and get results in an array. Thank you.

  • 1
    to resolve this issue you could use the library throttled-queue https://www.npmjs.com/package/throttled-queue, check this out https://stackoverflow.com/questions/44679614/can-someone-explain-an-enobufs-error#answer-44682450 – pbachman Mar 20 '21 at 07:17

1 Answers1

1

This issue generally comes in when you start to hit many requests. You can get all the promises in one array and resolve it. You can use 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);
});

If the above solution doesn't work you can use throlle-queue lib. It is easy to implement.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35