我有两个问题:
第一个问题我不能做异步函数:
let address = req.body.merchant_address;
let location = getGeolocation(address);
console.log(location);
async function getGeolocation(address) {
try {
const res = await googleMapsClient.geocode({ address: address }).asPromise();
const location = res.json.results[0].geometry.location;
console.log(location)
return location;
} catch (e) {
return res.status(422).json({
err: err
});
}
}
首先打印 Promise { <pending> }
然后只有我的坐标,我在上面的代码中做错了什么?
import maps from '@google/maps';
const googleMapsClient = maps.createClient({
key: 'my key'
});
第二个问题。当我构建项目时,启动后出现错误 Error: Can not find the module '@ google / maps
。我使用 babel src --out-dir backend
编译项目在 package.json file
。他为什么看不到"@ google/maps"
?
最佳答案
关于第一个问题:第一个 undefined
由代码片段的最后一行打印,因为它是在解析 geocode
回调之前执行的(异步)。
您可以使用 asPromise()
函数来摆脱回调并使代码与 async/await
同步,就像您已经开始的那样:
try {
const res = await googleMapsClient.geocode({
address: '1600 Amphitheatre Parkway, Mountain View, CA'
}).asPromise();
const location = res.json.results[0].geometry.location;
// your next stuff with location here...
} catch (e) {
console.error(e);
}
当然,整个代码段必须从 async
函数内调用。
关于javascript - 无法创建异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55096881/