[英]How to handle specific errors code in a geolocation promise?
我有一個獲取用戶位置的 function。 它是這樣工作的:
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,所以在 fetchGeolocation 結束之前觸發了 onSave() function。 所以我必須答應它。 寫這個會起作用:
function fetchGeolocation () { return new Promise((resolve, reject) =>{ navigator.geolocation.getCurrentPosition(resolve, reject); }); }; fetchGeolocation().then(res => onSave(res).catch(err => onError(err.message);
但我需要處理 catch 回調中的所有錯誤代碼。 我想處理 fetchGeolocation function 中的所有內容。 怎么做?
謝謝!
如果我正確地遵循了您的想法,那么下一個片段可能會幫助您:
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
,而是用錯誤字符串reject
promise 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.