【发布时间】:2017-08-24 03:14:12
【问题描述】:
我需要从 google geocode api 返回 lat-lng 坐标,然后用它做点什么。所以,我的代码是这样的:
async function getJson(url){
try {
const response = await fetch(url);
return await response.json();
}
catch (err) {
console.error(err.message);
}
}
function getLocationForName(address){
getJson(geoCodeUrl+address+apiKey).then(function(location){
return location.results[0].geometry.location;
});
}
someFunc(){
f['location'] = getLocationForName(city+f['street']+'+'+f['house']);
}
但是f['location'] 总是有 undefined 值
【问题讨论】:
-
您忘记从
getLocationForName转至return</strong> getJSON(...).then(...);。它将返回一个承诺,即f['location']将被分配承诺。如果这不是您想要的,请先等待承诺解决:getLocationForName(...).then(location => f['location'] = location)。如果您不能 100% 确定异步函数的工作原理,不妨看看 How do I return the response from an asynchronous call?。 -
是的,这个例子真的很有帮助,谢谢!所以,
getLocationForName(...).then(location => f['location'] = location)它看起来非常优雅,但我收到了这个错误:Uncaught TypeError: Cannot read property 'then' of undefined -
返回 await 也会返回 promise,而不是结果。您必须将结果分配给变量然后返回该变量的值。
-
今晚我的速度很慢=(你能打印一个例子吗?
-
"但是我得到了这个错误:..."你仍然需要在
getLocationForName中做return getJSON(...).then(...);。
标签: javascript google-maps asynchronous async-await