簡體   English   中英

在 javascript-nodejs 中使用 async-await 塊 inside.then() 塊時出現問題

[英]Problem when using async-await block inside .then() block in javascript-nodejs

問題
我使用 ipManager 作為中間件。 但由於某種原因,相同的 json object 被兩次添加到 Firestore。 此外,許多其他行正在重復。

代碼:

//imports...
exports.ipManager = (req, res, next) => {
  const ip = req.clientIp;
  const fullUrl = req.protocol + "://" + req.get("host") + req.originalUrl;
  console.log(fullUrl)
  if ((ip == "::1") & req.get("host").includes("localhost")) {
    console.log(
      "[+] ipManager functionalities restricted due to server running in local machine"
    );
    console.info(`[+] method=GET path=${fullUrl}`);
    next();
    return;
  }
  const _URL = req.originalUrl
  if (_URL.includes("documentation") || _URL.includes("weather") || _URL=="/") {
    console.log(_URL)
  } else {
    next()
    return
  }

  console.log("IP address " + ip);
  axios
    .get(`http://ip-api.com/json/${ip}`)

    // Show response data
    .then((res) => {
      const info = res.data;
      console.info(JSON.stringify(res.data));
      (async () => {
        try {
          const docRef = await addDoc(collection(db, "req_info_2022.1.22"), {
            country: info.country,
            countryCode: info.countryCode,
            region: info.region,
            regionName: info.regionName,
            city: info.city,
            zip: info.zip,
            lat: info.lat,
            lon: info.lon,
            timezone: info.timezone,
            isp: info.isp,
            org: info.org,
            as: info.as,
            ip: info.query,
            path: fullUrl,
          });
          console.log("Document written with ID: ", docRef.id);
        } catch (e) {
          console.error("Error adding document: ", e);
        }
      })()
    })
    .catch((err) => console.log(err));

  next();
};

這是控制台日志語句:
注意:請注意,console.logs 重復了兩次。 因此,兩個文檔(相同)被保存在 firebase 集合中。 應用程序日志

您的代碼有很多問題,但使用 async/await 代替 promise 鏈接和 IIFE 將使調試更容易。

//imports...
exports.ipManager = async (req, res, next) => {
  const ip = req.clientIp;
  const fullUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
  const isLocalMachineCalling =
    (ip == "::1") && req.get("host").includes("localhost");

  if (isLocalMachineCalling) {
    console.log(
      "[+] ipManager functionalities restricted due to server running in local machine"
    );
    console.info(`[+] method=GET path=${fullUrl}`);
    next();
    return;
  }
  if (["documentation", "weather", "/"].includes(req.originalUrl)) {
    console.log(req.originalUrl);
  } else {
    next();
    return;
  }

  console.log("IP address " + ip);
  const results = await axios.get(`http://ip-api.com/json/${ip}`);
  const info = results.data;

  try {
    const docRef = await addDoc(collection(db, "req_info_2022.1.22"), {
      country: info.country,
      countryCode: info.countryCode,
      region: info.region,
      regionName: info.regionName,
      city: info.city,
      zip: info.zip,
      lat: info.lat,
      lon: info.lon,
      timezone: info.timezone,
      isp: info.isp,
      org: info.org,
      as: info.as,
      ip: info.query,
      path: fullUrl,
    });
    console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }

  next();
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM