Javascript navigator.geolocation.getCurrentPosition函数在本地范围外调用时会导致未定义

Javascript navigator.geolocation.getCurrentPosition函数在本地范围外调用时会导致未定义,javascript,react-native,geolocation,navigator,Javascript,React Native,Geolocation,Navigator,调用navigator.geolocation.getCurrentPosition成功回调函数时,如何在函数外部访问该对象 假设我在导出的文件(称为UserLoc)中有一个函数 export const locateCurrentPosition = () => { const currentPosition = navigator.geolocation.getCurrentPosition( position => { console.log(posit

调用navigator.geolocation.getCurrentPosition成功回调函数时,如何在函数外部访问该对象

假设我在导出的文件(称为UserLoc)中有一个函数

export const locateCurrentPosition = () => {
  const currentPosition = navigator.geolocation.getCurrentPosition(
    position => {
      console.log(position);
      return position;
    },
    error => {
      console.log(error.message);
      return error;
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 1000
    }
  );

  return currentPosition;
};
现在,在我的一个组件js文件中,我想在componentDidMount()中调用这个函数

当我调用componentDidMount中的函数时,它总是返回一个未定义的值。当我记录这个时,它会在本地范围内打印出位置(即上面我使用console.log(position)的第一个代码块)。从成功回调中实际检索位置对象并在调用时将其返回到componentDidMount中的最佳方法是什么


我尝试了承诺,然后是控制台日志中的语句以及不同类型的返回,但我似乎总是没有定义。locateCurrentPosition函数中的返回语句似乎不起作用。有什么建议吗?

在新承诺之后添加了箭头((解决,拒绝)

navigator.geolocation.getCurrentPosition
返回
undefined
,调用
locateCurrentPosition
返回的值。Position仅传递给调用中提供的回调,可根据需要将其转换为承诺:

export const locateCurrentPosition = () => new Promise((resolve,reject)=> {
  navigator.geolocation.getCurrentPosition(
    position => {
      console.log(position);
      resolve(position);
    },
    error => {
      console.log(error.message);
      reject(error);
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 1000
    }
  );
});
并使用

locateCurrentPosition().then(position=>console.log(position))

另请参见新承诺后添加的箭头((解决、拒绝)

navigator.geolocation.getCurrentPosition
返回
undefined
,调用
locateCurrentPosition
返回的值。Position仅传递给调用中提供的回调,可根据需要将其转换为承诺:

export const locateCurrentPosition = () => new Promise((resolve,reject)=> {
  navigator.geolocation.getCurrentPosition(
    position => {
      console.log(position);
      resolve(position);
    },
    error => {
      console.log(error.message);
      reject(error);
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 1000
    }
  );
});
并使用

locateCurrentPosition().then(position=>console.log(position))

另请参见

这是否回答了您的问题?这是否回答了您的问题?谢谢,这非常有效。只需稍作修改。我因缺少=>,而遇到语法错误。我将在下面发布答案。感谢帮助。我对承诺不太熟悉。我尝试使用waits和async,因为我认为它们与pro类似mises,但没有任何运气。更正,我编辑了你的帖子以显示丢失的箭头。再次感谢。谢谢,这非常有效。只需稍加修改。由于缺少=>,我遇到语法错误。我将在下面发布答案。感谢帮助。我对承诺不太熟悉。我尝试使用waits和async,因为我认为它们类似于承诺,但没有任何运气。更正,我编辑了你的帖子以显示丢失的箭头。再次感谢。