从Google Places getDetails回调异步返回值

问题描述

是否可以通过callback函数使Google地方信息getDetails异步或返回其值?

本质上,在我的react应用中,我正在尝试执行以下操作:

  1. placeId传递给Google Places API
  2. 等待Google带回一些地点信息(地址,照片等)
  3. 调用我的本地api来处理来自Google的数据

虽然会发生

  1. google去获取数据
  2. 调用我的api,但google尚未恢复数据

我尝试使用useState,但是状态不会立即更新,因此我不确定在继续通话之前如何“等待”谷歌场所完成数据获取

我正在尝试做的事的例子(显然是错误的)

    const [value,setValue] = useState('')

    const foo = async (placeId) => {
      var service = new window.google.maps.places.PlacesService(
        predictionsRef.current,)
      await service.getDetails(
        {
          placeId,fields: ['photos'],},async place =>
          await setValue(
            place.photos[0].getUrl({ maxWidth: 1280,maxHeight: 720 }),),)

      // I want 'value' to have google place data before the axios call
      await axios.post(...)
    }

到目前为止,我已经查看了以下链接,但无法拼凑出我需要的内容

解决方法

你可以这样,

const [value,setValue] = useState('')
const [placeID,setPlaceID] = useState(null)

从Google placeDetails API返回承诺的函数,

const getPlaceDetails = (ref) => {
  return new Promise(function (resolve,reject) {
    let placesService = new window.google.maps.places.PlacesService(ref);
    placesService.getDetails(
      {
        placeId,fields: ['photos'],},(place) => {
        resolve(place.something);
      }
    );
  });
};

在placeID更改时触发的效果

useEffect(() => {
  async function doStuff() {
    let placesResponse = await getPlaceDetails(ref);
    let myResponse = await yourAPICall(placesResponse);
    setValue(placesResponse);
  }
  if(placeID !==null){
    doStuff();
  }
},[placeID]);

我尚未测试此代码,但希望这种方法有所帮助。