尝试在async
函数中包装Google Maps API调用时,我无法在控制台中记录响应 - 我是否尝试访问返回的值时出错了地图API函数?我的代码包含两个应该按顺序运行的异步进程,然后是一个处理这两个进程的函数。我们的想法是提供一个包含位置的查询字符串,Maps API将查找它,然后在控制台中返回格式化的地址。
Google地图处理:
const mapsApiKey = 'API_KEY';
const googleMapsClient = require('@google/maps').createClient({
key: mapsApiKey
});
async function getAddress(queryString) {
googleMapsClient.geocode({
address: queryString
}, function (err, response) {
if (!err) {
let formattedAddress = response.json.results[0]['formatted_address'];
return formattedAddress;
} else {
return err;
}
});
}
Console.log进程:
async function showResult(address) {
return("result from Promise: " + getAddress());
}
主要异步功能:
async function handleAddress(inputString) { // originally async function endpointHandler(request, response) {
try {
let awaitedResult = await getAddress(inputString);// function we want as var, with params
let waitingFunc = await showResult(formattedAddress);// should only executes after awaitedResult gets resolved!!!
console.log(waitingFunc());
} catch(err) {
// handle errors here
}
}
handleAddress('London');