node.js - 在 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);
}
);
});
推荐阅读
- typescript - 与非空对象很好地相交的空对象类型
- javascript - 如何通过 react-query 在客户端显示服务器端验证消息?
- python - 如何呈现用户复选框,然后将列表保存到选中的复选框?
- vba - 如何在VBA中仅替换字符串起始行
- python - 尝试在 flat_map 中加载数据集时出现错误“TypeError:预期的 str、字节或 os.PathLike 对象,而不是张量”
- mongodb - Mongoose:从一堆文件中更新一个文件
- angular - 主页中的控制组件(Angular/Ionic)
- python - 我正在尝试使用 pysimplegui,但我无法重新运行窗口
- c - 为什么使用gets()函数的返回值会出现分段错误?
- node.js - 与 ECS 一起使用时,AWS ALB 返回一个空页面