javascript – Redux Saga navigator.geolocation.getCurrentPosition

前端之家收集整理的这篇文章主要介绍了javascript – Redux Saga navigator.geolocation.getCurrentPosition前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我使用redux saga创建应用程序,我遇到地理位置问题.
其实我找到了解决方案,但我不明白它是如何工作的.

function userPositionPromised() {
  const position = {}
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition (
      location  => position.on({location}),error     => position.on({error}),{ enableHighAccuracy: true }
    )
  }
  return { getLocation: () => new Promise(location => position.on = location) }
}

function* getUserLocation() {
  yield put({type: GET_LOCATION_REQUESTED});
  const { getLocation } = yield call(userPositionPromised)
  const { error,location } = yield call(getLocation)
  if (error) {
    console.log('Failed to get user position!',error)
    const { message,code } = error;
    yield put({type: GET_LOCATION_Failed,payload: { code,message }});
  } else {
    console.log('Received User Location',location)
    const { latitude: lat,longitude: lng } = location.coords;
    yield put({type: GET_LOCATION_SUCCESS,payload: { lat,lng } });
  }
}

我理解getUserLocation但是当谈到userPositionPromised时我得不到它.特别是这部分:

      location  => position.on({location}),

 return { getLocation: () => new Promise(location => position.on = location) }
最佳答案
我试过运行上面的代码,我在这里得到了一个错误

location  => position.on({location}),

对我有用的是创建一个在检索位置时解决的承诺定义.例如:

const getUserLocation = () => new Promise((resolve,reject) => {
 navigator.geolocation.getCurrentPosition(
  location => resolve(location),error => reject(error),)
})

然后你就像在任何其他服务中一样从生成器中调用它.

function* myGenerator() {
 const location = yield call(getUserLocation)
 {latitude,longitude} = location.coords;
}

请享用

原文链接:https://www.f2er.com/js/429254.html

猜你在找的JavaScript相关文章