【问题标题】:How can I call an asynchronous method using the Geolocation API?如何使用 Geolocation API 调用异步方法?
【发布时间】:2019-06-13 23:14:18
【问题描述】:

在我的 React 应用程序中,我希望能够使用 Geolocation API 调用具有用户当前位置的 API 端点。

我有以下方法,当用户单击按钮时会触发

findMeetings = async () => {

  const location = window.navigator && window.navigator.geolocation

  if (location) {
    location.getCurrentPosition((position) => {
    let url = `meetings/find?lat=${position.coords.latitude}&lng=${position.coords.longitude}&radius=${this.state.radius}`;
    let result = await fetch(`https://localhost:44303/api/${url}`, {
      method: 'get'
     }).then(response => response.json());
    this.setState({ meetings: result.meetings })
   }, (error) => {

  })
}

我收到以下错误:

解析错误:await 是保留字

我认为这是因为我在 getCurrentPosition 内部调用了一个异步方法 - 谁能帮助我了解这里的问题以及如何解决它?

【问题讨论】:

    标签: reactjs async-await fetch


    【解决方案1】:

    这可能是因为即使父方法有关键字 async (findMeetings),location.getCurrentPosition(..) 函数也没有 async 关键字。

    所以尝试这样的事情可能会有所帮助:

    location.getCurrentPosition(async position => {
      .. actual code
    })
    

    让我知道这是否有效,干杯:)

    【讨论】:

    • 很高兴能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 2020-03-10
    • 2016-04-07
    • 1970-01-01
    • 2017-03-06
    • 2020-06-08
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多