等到条件成立?

时间:2011-08-25 15:40:08

标签: javascript geolocation

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

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

但是,由于缺少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...
});

7 个答案:

答案 0 :(得分:25)

就个人而言,我使用waitfor()函数封装setTimeout()

//**********************************************************************
// function waitfor - Wait until a condition is met
//        
// Needed parameters:
//    test: function that returns a value
//    expectedValue: the value of the test function we are waiting for
//    msec: delay between the calls to test
//    callback: function to execute when the condition is met
// Parameters for debugging:
//    count: used to count the loops
//    source: a string to specify an ID, a message, etc
//**********************************************************************
function waitfor(test, expectedValue, msec, count, source, callback) {
    // Check if condition met. If not, re-check later (msec).
    while (test() !== expectedValue) {
        count++;
        setTimeout(function() {
            waitfor(test, expectedValue, msec, count, source, callback);
        }, msec);
        return;
    }
    // Condition finally met. callback() can be executed.
    console.log(source + ': ' + test() + ', expected: ' + expectedValue + ', ' + count + ' loops.');
    callback();
}

我以下列方式使用waitfor()函数:

var _TIMEOUT = 50; // waitfor test rate [msec]
var bBusy = true;  // Busy flag (will be changed somewhere else in the code)
...
// Test a flag
function _isBusy() {
    return bBusy;
}
...

// Wait until idle (busy must be false)
waitfor(_isBusy, false, _TIMEOUT, 0, 'play->busy false', function() {
    alert('The show can resume !');
});

答案 1 :(得分:13)

这正是承诺的发明和实施(因为OP问他的问题)。

查看所有各种实现,例如promisejs.org

答案 2 :(得分:12)

您需要使用setTimeout

function checkAndSubmit(form) {
    var location = getLocation();
    if (!location) {
        setTimeout(checkAndSubmit, 500, form); // setTimeout(func, timeMS, params...)
    } else {
        // Set location on form here if it isn't in getLocation()
        form.submit();
    }
}

...其中getLocation查找您的位置。

答案 3 :(得分:7)

您可以使用超时尝试重新提交表单:

$('#route-form').submit(function(event) {
    // User submits form, we need their location...
    if(current_location==null) {
        toastMessage('Waiting for your location...');
        setTimeout(function(){ $('#route-form').submit(); }, 500); // Try to submit form after timeout
        return false;
    } else {
        // Continue with location found...
    }
});

答案 4 :(得分:2)

使用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

答案 5 :(得分:0)

class App extends React.Component {

componentDidMount() {
   this.processToken();

}
 processToken = () => {
    try {
        const params = querySearch(this.props.location.search);
        if('accessToken' in params){
            this.setOrderContext(params);
            this.props.history.push(`/myinfo`);
        }
    } catch(ex) {
      console.log(ex);
    }
    }

   setOrderContext (params){
     //this action calls a reducer and put the token in session storage
     this.props.userActions.processUserToken({data: {accessToken:params.accessToken}});
}

render() {
    return (

        <Switch>
            //myinfo component needs accessToken to retrieve my info
            <Route path="/myInfo" component={InofUI.App} />
        </Switch>

    );
}

然后在InofUI.App内部

componentDidMount() {
        this.retrieveMyInfo();
    }

    retrieveMyInfo = async () => {
        await this.untilTokenIsSet();
        const { location, history } = this.props;
        this.props.processUser(location, history);
    }

    untilTokenIsSet= () => {
        const poll = (resolve) => {
            const { user } = this.props;
            const { accessToken } = user;
            console.log('getting accessToken', accessToken);
            if (accessToken) {
                resolve();
            } else {
                console.log('wating for token .. ');
                setTimeout(() => poll(resolve), 100);
            }
        };
        return new Promise(poll);
    } 

答案 6 :(得分:0)

尝试像这样使用setIntervalclearInterval ...

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...
    // Checks status every half-second
    var watch = setInterval(task, 500)

    function task() {
        if (current_latlng != null) {
            clearInterval(watch)
            watch = false
            return callback()
        } else {
            toastMessage('Waiting for your location...');

        }
    }

    function callback() {
        // Continue on with location found...
    }
});