Ask a question about JS assignment

in order to get a WeChat Mini Programs, you need to call the user location information later, but the values in the console outside wx.getLocation are all empty. How to write? Only the following console.log (latitude) can get the value obtained in it?

.

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

.

Oct.28,2021

pseudo code

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)
})

you call something asynchronous, so you can only do what you want in the callback function


it is recommended that the landlord first learn about Asynchronous and Synchronize

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