Javascript 在函数内获取
Javascript Fetch within a function
我试图从 google 地图 API 中获取一些 JSON 数据。当我调用这个函数时,我希望 "test" 变量变成 45。但它仍然是 0。
下面的代码看起来有点愚蠢,因为我想简化事情。我有一个有效的 API 密钥,请不要质疑。我是不是误解了 Javascript 或 fetch api 之类的?请帮助..非常感谢!
function toLat(location) {
var lat = 0;
if (location.length > 0) {
var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address=Seattle&key=Your_API_Key";
fetch(googleURL)
.then(function(response) {
return response.json();
})
.then(function(data) {
data.results.forEach(function(item) {
lat = item.geometry.location.lat;
});
console.log(lat); // here is, e.g. '45'
});
}
return lat;
}
var test = toLat();
console.log(test); // why still '0'?
获取apireturns一个Promise。这是一个异步过程,因此您需要在此处更新 test
的值:
then(function(data){ // here })
我试图从 google 地图 API 中获取一些 JSON 数据。当我调用这个函数时,我希望 "test" 变量变成 45。但它仍然是 0。
下面的代码看起来有点愚蠢,因为我想简化事情。我有一个有效的 API 密钥,请不要质疑。我是不是误解了 Javascript 或 fetch api 之类的?请帮助..非常感谢!
function toLat(location) {
var lat = 0;
if (location.length > 0) {
var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address=Seattle&key=Your_API_Key";
fetch(googleURL)
.then(function(response) {
return response.json();
})
.then(function(data) {
data.results.forEach(function(item) {
lat = item.geometry.location.lat;
});
console.log(lat); // here is, e.g. '45'
});
}
return lat;
}
var test = toLat();
console.log(test); // why still '0'?
获取apireturns一个Promise。这是一个异步过程,因此您需要在此处更新 test
的值:
then(function(data){ // here })