0
const getWeather = (req, res, next)=>{
    const cities = req.body.cities;
    let weatherInfo = [];
    try{
    cities.forEach(async(city)=>{
        const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.API_KEY}`);
        if(!response.ok){
            weatherInfo.push({error : "No Data Found"});
        }
        const responseData = await response.json();
        const cityData = {city : responseData.main.temp - 273.15};
        weatherInfo.push(cityData);
    });
    
    }
    catch(err){
        const error = err.message || "Something Went Wrong.. Please Try again!!";
        return next(error);
    }

    res.json(weatherInfo);
}

exports.getWeather = getWeather

I want to push cityData inside the weatherInfo array, but it is not happening. I am always getting empty array as output.

Himashu
  • 21
  • 4
  • 2
    You can't get **a**synchronous results synchronously. Your `res.json` call runs before any of the calls to the `forEach` callback. – T.J. Crowder Aug 15 '22 at 06:36
  • Instead, write an `async` function that `getWeather` can call that gets the weather information asynchronously, [along these lines](https://pastebin.com/3mrrArEK). (Note: Don't just pass an `async` function to Express as a route handler; Express completely ignores the promise the function would return, including ignoring promise rejections. Instead, see the link: Have the route handler call an `async` function and explicitly handle promise rejection. [You *can* do it all in one function, but it's clearer with the separation.) – T.J. Crowder Aug 15 '22 at 06:41

0 Answers0