【发布时间】:2017-03-09 13:23:04
【问题描述】:
我试图从谷歌地图 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'?
【问题讨论】:
-
fetch是异步的。toLat立即返回。 -
你需要了解异步代码。在提取 JSON 数据时,您的其余代码将继续运行。因此,您的 return 语句是无用的。您需要根据您的 console.log 语句的值放置代码。
-
@LeeTaylor 感谢您的解释!所以不能把值拿出来用在别处吗?
-
@Emile。您需要将依赖该值的代码放入接收数据时调用的函数中(就像使用 .log 语句一样)。因此,它需要一种不同的思维方式和编码方式。
标签: javascript function variables scope fetch-api