如何处理地理定位承诺中的特定错误代码?

How to handle specific errors code in a geolocation promise?

我有一个获取用户位置的函数。它是这样工作的:

const fetchGeoLocation: SearchService["fetchGeoLocation"] = async () => {
  const geo = navigator.geolocation;
  if (!geo) throw new Error("error.geolocation-unavailable");
  const handleError = (err: any) => {
    if (err.code === 1) throw new Error("error.geolocation-permission_denied");
    if (err.code === 2) throw new Error("error.geolocation-unavailable");
    if (err.code === 3) throw new Error("error.geolocation-timeout");
  };
  const handleSuccess = (position) => {
    return { location: [position.coords.longitude, position.coords.latitude] };
  };
  geo.getCurrentPosition(handleSuccess, handleError, { maximumAge: 10000 });
};


  const onUpdateLocation = async () => {
    onLoad();
    fetchGeoLocation()
      .then((res) => onSave(res.data))
      .catch(({ message }) => onError(message));
  };

因为不是promise,onSave() 函数在fetchGeolocation 结束前触发。所以我必须答应它。写这个会起作用:

 function fetchGeolocation () {
   return new Promise((resolve, reject) =>{
     navigator.geolocation.getCurrentPosition(resolve, reject);
   });
 };

fetchGeolocation()
  .then(res => onSave(res)
  .catch(err => onError(err.message);

但我需要处理 catch 回调中的所有错误代码。我想处理 fetchGeolocation 函数中的所有内容。怎么做?

谢谢!

如果我正确地遵循了您的想法,那么下一个片段可能会对您有所帮助:

const fetchGeoLocation: SearchService["fetchGeoLocation"] = async () => {
  return new Promise((resolve, reject) => {
    const { geolocation } = navigator;
    if (!geolocation) reject("error.geolocation-unavailable");
    const handleError = ({ code }) => {
      if (code === 1) reject("error.geolocation-permission_denied");
      if (code === 2) reject("error.geolocation-unavailable");
      if (code === 3) reject("error.geolocation-timeout");
    };
    const handleSuccess = (position) => {
      resolve({ location: [position.coords.longitude, position.coords.latitude] });
    };
    geo.getCurrentPosition(handleSuccess, handleError, { maximumAge: 10000 });
  });
};

注意,不是 throw'ing,而是 reject'ing 带有错误字符串的承诺。