问一个关于JS赋值的问题

在弄一个微信小程序,需要在后面调用用户位置信息,但是在wx.getLocation外面console里面的数值时候全部为空。怎么写?下面的console.log(latitude)才能取得里面获取到的数值?

.......

var latitude
var longitude
wx.getLocation({
  type: 'wgs84',
  success: (res) => {
    latitude = res.latitude
    longitude = res.longitude
  }
})
console.log(latitude)

..........

阅读 1.8k
3 个回答

伪代码

function getLocation(){
    return new Promise(resolve => {
        wx.getLocation({
          type: 'wgs84',
          success: (res) => {
            latitude = res.latitude
            longitude = res.longitude
            resolve();  
          }
        })
    })
}

getLocation().then(data => {
    console.log(latitude)
})

你调用了异步的东西,这样你只能在回调函数里面去做你想做的事

建议楼主先去了解一下异步和同步

return new Promise(resolve=>
wx.getLocation({
  type: 'wgs84',
  success: resolve
})).then((res)=>{
    console.log(res.latitude,res.longitude);
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题