gpt4 book ai didi

javascript - 等到条件成立?

转载 作者:行者123 更新时间:2023-12-03 02:56:05 25 4
gpt4 key购买 nike

我在 JavaScript 中使用 navigator.geolocation.watchPosition,并且我想要一种方法来处理用户可能在 watchPosition 之前提交依赖于位置的表单的可能性> 已找到其位置。

理想情况下,用户会定期看到“等待位置”消息,直到获得位置,然后提交表单。

但是,由于 JavaScript 缺少 wait 函数,我不确定如何在 JavaScript 中实现此功能。

当前代码:

var current_latlng = null;
function gpsSuccess(pos){
//console.log('gpsSuccess');
if (pos.coords) {
lat = pos.coords.latitude;
lng = pos.coords.longitude;
}
else {
lat = pos.latitude;
lng = pos.longitude;
}
current_latlng = new google.maps.LatLng(lat, lng);
}
watchId = navigator.geolocation.watchPosition(gpsSuccess,
gpsFail, {timeout:5000, maximumAge: 300000});
$('#route-form').submit(function(event) {
// User submits form, we need their location...
while(current_location==null) {
toastMessage('Waiting for your location...');
wait(500); // What should I use instead?
}
// Continue with location found...
});

最佳答案

使用 Promise 的现代解决方案

function waitFor(conditionFunction) {

const poll = resolve => {
if(conditionFunction()) resolve();
else setTimeout(_ => poll(resolve), 400);
}

return new Promise(poll);
}

使用

waitFor(_ => flag === true)
.then(_ => console.log('the wait is over!'));

async function demo() {
await waitFor(_ => flag === true);
console.log('the wait is over!');
}

引用文献
Promises
Arrow Functions
Async/Await

关于javascript - 等到条件成立?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7193238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com