为了限制 API 调用的等待时间,我已经为两个承诺竞速直到完成(我的异步函数和一个超时函数)设置了我的超时函数。
它用于 react-native-maps 上的 onFindMe 按钮。单击按钮时,它会立即按照设计找到位置,但即使我将超时设置为 1 毫秒,它仍然会找到位置并将其存储在 currentLoco 变量中。
我正在使用 Location.getCurrentPositionAsync({}) 来自 expo-location 来获取位置。
我的超时功能没有按设计工作,或者它获取位置的速度快于 1 毫升。这可能吗?我假设它是我的代码,在这种情况下请告诉我修复方法!
超时功能:
export const asyncCallWithTimeout = async (asyncPromise, timeLimit) => {
let timeoutHandle;
const timeoutPromise = new Promise((_resolve, reject) => {
timeoutHandle = setTimeout(
() => reject(new Error("Async call timeout limit reached")),
timeLimit
);
});
return Promise.race([asyncPromise, timeoutPromise]).then((result) => {
clearTimeout(timeoutHandle);
return result;
});
};
这是我的按钮片段
const onFindMe = async () => {
try {
setIsLoading(true);
let currentLoco = await asyncCallWithTimeout(
Location.getCurrentPositionAsync({}),
1
);
if (!currentLoco) throw new Error("Timeout when fetching location");
setIsLoading(false);
console.log(currentLoco);
} catch (err) {
setIsLoading(false);
setError(err);
}
};
谢谢!