返回调用并等待另一个异步函数的异步函数的结果

时间:2021-07-17 21:26:13

标签: javascript react-native google-places-api

如果允许fine_location_permission,我依靠谷歌地点和地理编码API根据他的坐标获取当前用户的位置,否则使用默认位置。该位置用于根据距离过滤产品,因此必须在获取产品列表之前获取它。

我使用的代码导致了一个烦人的问题,即函数 getCurrentLocation 在从 API(另一个异步函数)获取结果之前返回一个空对象。问题是,如何优化这两个函数,让第二个函数等待第一个函数的结果,然后将结果返回给组件?

export const getCoordinates = async (
  queryLocation: string | null,
  queryCoordinates: any | null
) => {
  try {
    const json = await Geocoder.from(queryCoordinates || queryLocation);
    const result = json.results[0].geometry.location;
    const location = json.results[0].formatted_address;

    const currentCoordinates: any = {};
    currentCoordinates["latitude"] = result["lat"];
    currentCoordinates["longitude"] = result["lng"];
    const loc = { coordinates: currentCoordinates, location };
    return loc;
  } catch (err) {
    console.log(err, "getting coordinates error");
    return defaultLocation;
  }
};

const getLocationPermissions = async () => {
  const granted = await request(PERMISSION_TYPE, {
    title: "App",
    message: "App requires access to your location ",
    buttonPositive: "Accept",
  });
  return granted === RESULTS.GRANTED;
};

 const getCurrentLocation = async () => {
      const granted = await getLocationPermissions();
      let result: any = {};
      if (granted) {
        Geolocation.getCurrentPosition(
          async (position) => {
            const coords = {
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
            };
            result = await getCoordinates(null, coords);
            console.log(result)
            return result;
          },
          (error) => {
            console.log(error, "current location fetch error");
            return defaultLocation;
          },
          { enableHighAccuracy: true, timeout: 1500000 }
        );
      }
      return result;
    };

[编辑]

在阅读并执行下面@Bergi 的评论后,我终于解决了这个问题。

我重新编写了 getCurrentLocation 函数如下:

const getCurrentLocation = async () => {
  const granted = await getLocationPermissions();
  let result: any = {};
  if (granted) {
    return new Promise(async (resolve) => {
      await Geolocation.getCurrentPosition(
        async (position) => {
          const coordinates = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          };
          result = await getCoordinates(null, coordinates);
          resolve(result);
        },
        (error) => {
          console.log(error, "current location fetch error");
        }
      );
    })
  }
};

0 个答案:

没有答案