【问题标题】:Not getting response in time when using geo.find() in node.js在 node.js 中使用 geo.find() 时没有及时得到响应
【发布时间】:2019-09-26 11:23:27
【问题描述】:

我试图从下面的代码中得到响应:-

  let latlongdata;
  if (userInfo.address != "" && userInfo.country != "") {
    let add = userInfo.address + "," + userInfo.country;
    geo.find(add, function(err, res) {
      latlongdata = res[0].location.lat;
      console.log("Inside output", res[0].location.lat); // Got response
    });
    console.log("Outside output", getletlong); // No response
  }
}

在安慰“内部输出”时,我得到了回应, 在安慰“外部输出”时我没有得到回应

我也尝试过使用异步等待,下面是代码:-

if (userInfo.address != "" && userInfo.country != "") {
  add = userInfo.address + "," + userInfo.country;
  [err, data] = await to(geo.find(add));

  console.log("output", data);
  console.log("error", err);
} 

当我使用 setTimeOut() 时,我终于得到了响应

let latlongdata;
if (userInfo.address != "" && userInfo.country != "") {
  add = userInfo.address + "," + userInfo.country;
  geo.find(add, function(err, res) {
    if (res) {
      userInfo.latitude = res[0].location.lat;
    }
  });
}
userInfo.role_id = 2;
setTimeout(async () => {
  [err, user] = await to(User.create(userInfo));
}, 300);

但我认为这不是正确的方法,而且我认为这在每种情况下都不适用于我,请谁能告诉我前两种方法我做错了什么。

我用过。:- "google-geocoder": "^0.2.1"

【问题讨论】:

  • edit您的问题告诉我们您使用的地理定位包。换句话说,请显示创建您在代码中使用的geo 对象的代码。
  • @O.Jones 我为此使用了 "google-geocoder": "^0.2.1"

标签: node.js geolocation google-geolocation


【解决方案1】:

我做了一些研发,找到了下面的解决方案

let add = userInfo.address + "," + userInfo.country;
return new Promise((resolve, reject) => {
  geo.find(
    "India",
    (err, res) => {
      if (res) {
        resolve(res);
      }
      if (err) {
        reject(err);
      }
    },
    err => {
      reject(err);
    }
  );
});

【讨论】:

    猜你喜欢
    • 2016-01-09
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 2019-01-23
    • 2020-07-06
    • 2019-09-10
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多