NodeJS 对象在“response.on”内部得到更新,但更新不会在[duplicate]外部得到反映

omjgkv6w  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(163)

此问题已在此处有答案

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference(7个回答)
6小时前关闭
当我将对象 result 发送回前端时,它不会得到更新。在前端,它只显示发送了一个空对象。

  • url* 已定义。API调用工作正常。当控制台登录在 response.on 中时,结果显示了正确的行为。然而,在 https 请求之外,它显示一个空对象,并且没有添加键值对。
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);

});

前端结果输出= {}

polhcujo

polhcujo1#

您需要将https.get调用 Package 到promise中。result在return语句中是空对象的原因是因为https.get是异步的,并且您不需要等待dataerror处理程序被调用。

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

相关问题