javascript - 如何在javascript中从内部承诺中获取数据
问题描述
我正在尝试使用 HTML5 Geolocation API 和 Google Maps Geocoding API 获取用户的国家/地区名称。我正在使用自定义模式来优雅地请求权限。如何访问返回的国家/地区短名称?目前我得到undefined
.
function fetchCountry() {
showCustomModal('To show data most relevant to you we need your location', {
options: ['done', 'cancel']
})
.then(function(value) {
if(value == 'cancel') return;
navigator.geolocation.getCurrentPosition(function (position) {
//if user agrees to share location info
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}`)
.then(response => response.json())
.then(function (response) {
//checking geocoding api response for errors
if (response.status != 'OK' || !response.results[0]) return;
for (let addressComponent of response.results[0].address_components) {
if (addressComponent.types.includes('country'))
return addressComponent.short_name; //returning country short name
}
});
}, function () {
//if does not gets the current position show error message
//do something...
});
});
}
let country = fetchCountry();
解决方案
你可以引入一个 promise,当 subseuqnet 异步请求被解析(成功)或被拒绝(失败)时被解析,如下所示
function fetchCountry() {
// Add return statement here
return showCustomModal('To show data most relevant to you we need your location', {
options: ['done', 'cancel']
})
.then(function(value) {
if(value == 'cancel') return;
// Introduce the promise which will asynchronously process the post-modal request logic, and return a result on completion
// or failure of that request
return new Promise(function(resolve, reject) {
navigator.geolocation.getCurrentPosition(function (position) {
//if user agrees to share location info
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}`)
.then(response => response.json())
.then(function (response) {
//checking geocoding api response for errors
if (response.status != 'OK' || !response.results[0]) {
reject(); // Call reject to relay and failed request
}
for (let addressComponent of response.results[0].address_components) {
if (addressComponent.types.includes('country'))
resolve(addressComponent.short_name); //returning country short name, via resolve
}
});
}, function () {
//if does not gets the current position show error message
//do something...
reject('Failed to get position') // Call reject to relay and failed request
});
})
});
}
fetchCountry().then(function(country) {
//access country here
}).catch(function(err) {
//handle error here
})
推荐阅读
- c# - docker容器之间的HTTPS通信问题
- c# - HttpClient PostAsync 抛出异常
- c - 是否可以在 bison.yh 文件中暴露 yyin ?
- python - 在二维列表或数组中找到最接近的距离值?
- c# - 团结 | 找不到类型或命名空间名称“Google”
- python - PyMongo 替换嵌套文档中的字符串
- prolog - 谓词 solve/2 它的第一个参数是非空列表,第二个参数是由第一个参数的零个或多个附加副本组成的列表
- python - 我需要用 100000 个点在 python turtle 中绘制一个图
- java - 目标是为给定字符串写下一个方法,该方法通过它们在字典中的外观返回一个字符串数组
- typescript - 无法在量角器打字稿代码中跳出循环