最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在node.js中使用geo.find()时无法及时获得响应

运维笔记admin17浏览0评论

在node.js中使用geo.find()时无法及时获得响应

在node.js中使用geo.find()时无法及时获得响应

我试图从下面的代码中获取响应:-

  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”

回答如下:

我已经进行了一些研发,找到了以下解决方案

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);
    }
  );
});
发布评论

评论列表(0)

  1. 暂无评论