gpt4 book ai didi

javascript - 如何从 JavaScript 中的内部 Promise 获取数据

转载 作者:行者123 更新时间:2023-12-03 01:16:27 25 4
gpt4 key购买 nike

我正在尝试使用 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 异步请求得到解决(成功)或拒绝(失败)时,该 promise 就会得到解决,如下所示

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
})

关于javascript - 如何从 JavaScript 中的内部 Promise 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51994499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com