0

The object result does not get updated when I send it back to the front end. At the front-end, it just shows that an empty object has been sent.

url is defined. The API call works correctly. The result when console logged inside response.on shows the correct behaviour. However, outside the https request it shows an empty object and the key value pairs are not added.

app.post("/getWeather",(req,res,next)=>{

    console.log(req.body.cities);

    const cities=req.body.cities;

    const result={};

    cities.map((city)=>{

        https.get(url,(response)=>{

            response.on("data",(data)=>{
                const wdata=JSON.parse(data);
                const temperature=wdata.main.temp;
                result[city]=temperature;
            });


        }).on("error",(err)=>{
            console.log(err);

            result[city]="NA";
        });
    });

    return res.json(result);

});

Result output at front-end = {}

Could someone please provide the corrected code?

1 Answers1

-1

You need to wrap https.get calls into promises. The reason why result is an empty object at the return statement is because https.get is asynchronous, and you're not waiting for the data and error handlers to be called.

app.post("/getWeather", async (req, res, next) => {
  console.log(req.body.cities);

  const cities = req.body.cities;

  const result = {};

  const promises = [];

  cities.forEach((city) => {
    promises.push(
      new Promise((resolve) => {
        https
          .get(url, (response) => {
            response.on("data", (data) => {
              const wdata = JSON.parse(data);
              const temperature = wdata.main.temp;
              result[city] = temperature;
            });
          })
          .on("end", () => {
            resolve();
          })
          .on("error", (err) => {
            console.log(err);

            result[city] = "NA";

            resolve();
          });
      })
    );
  });

  await Promise.all(promises);

  return res.json(result);
});

lucassilvas1
  • 54
  • 1
  • 8