javascript - 无法创建异步函数

标签 javascript node.js google-maps

我有两个问题:

第一个问题我不能做异步函数:

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/

相关文章:

node.js bodyParser 错误

google-maps - 如何沿用户在 Swift 中移动的方向旋转 GMSMarker?

javascript - 在 javascript/jquery 中读取文件

javascript - 条形码扫描仪仅在用户位于输入框时产生 "keypress"事件。当用户不在输入框上时要听什么事件?

javascript - 如何将一个外部js文件链接到另一个外部js文件?

Node.js 初学者教程脚本 - 错误代码 : ERR_EMPTY_RESPONSE

javascript - 创建在 Express 请求中返回的错误消息的正确方法是什么?

javascript - RTCPeerConnection 与 RTCConfiguration 在 Firefox 上中断

google-maps - 将 Google 建筑物 ID 映射到 Openstreetmap 建筑物 ID

google-maps - Google map 和 WCAG 2.0 A 级