javascript – Redux Saga navigator.geolocation.getCurrentPosition

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

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

  1. function userPositionPromised() {
  2. const position = {}
  3. if (navigator.geolocation) {
  4. navigator.geolocation.getCurrentPosition (
  5. location => position.on({location}),error => position.on({error}),{ enableHighAccuracy: true }
  6. )
  7. }
  8. return { getLocation: () => new Promise(location => position.on = location) }
  9. }
  10. function* getUserLocation() {
  11. yield put({type: GET_LOCATION_REQUESTED});
  12. const { getLocation } = yield call(userPositionPromised)
  13. const { error,location } = yield call(getLocation)
  14. if (error) {
  15. console.log('Failed to get user position!',error)
  16. const { message,code } = error;
  17. yield put({type: GET_LOCATION_Failed,payload: { code,message }});
  18. } else {
  19. console.log('Received User Location',location)
  20. const { latitude: lat,longitude: lng } = location.coords;
  21. yield put({type: GET_LOCATION_SUCCESS,payload: { lat,lng } });
  22. }
  23. }

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

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

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

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

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

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

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

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

请享用

猜你在找的JavaScript相关文章