【问题标题】:Having trouble using async await with Google Maps Geocode API在 Google Maps Geocode API 中使用异步等待时遇到问题
【发布时间】:2019-06-28 20:08:51
【问题描述】:

我正在使用 Google Maps Geocode API 并尝试使用异步等待。我已经定义了几个处理请求的函数:

function googleGeoCode(address) {
  const googleMapsClient = require('@google/maps').createClient({
    key: 'googleMapsApiKeyGoesHere',
    Promise: Promise
  });

  return googleMapsClient.geocode({ address: address }).asPromise();
}

async function getGeoCode(address, errors, res) {
  try {
    const result = await googleGeoCode(address);
    return result;
  } catch (error) {
    errors.googleMapsClient = error;
    return res.status(400).json(errors);
  }
}

然后我在我的快速路线中使用 getGeoCode 函数:

const geoResponse = getGeoCode(req.body.address, errors, res);

函数的等待部分无法正常工作。如果我控制台记录 geoResponse 我得到Promise { <pending> }

我是使用异步等待的新手,我不确定我是否在这里做错了什么。非常感谢任何帮助!

【问题讨论】:

    标签: node.js async-await google-geocoder


    【解决方案1】:

    一个异步函数总是返回一个promise或者将返回值包装成promise,你必须像这样解决promise

     const geoResponse = getGeoCode(req.body.address, errors, res);
    
        geoResponse.then((result)=>{
    
        console.log(result)
        }).catch((err)=>{
         console.log(err);
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 2021-12-18
      • 2016-01-11
      相关资源
      最近更新 更多