async/await 还是同步怎么办?
get : async function(e) { let $that = this ; let $distance = await getDistance($that.data.info._point); if ($distance <= 8000) { //step1 } else { //step2 } }, let getDistance = async (point) => { let $geo = null ; await wx.getLocation({ type: "gcj02" , altitude: true , success: res => { $geo = [res.longitude, res.latitude]; }, fail: err => { $geo = [180, -80]; }, complete: () => { let $pointJson = JSON.stringify(point); let $pointGeo = JSON.parse($pointJson); let $point = $pointGeo.coordinates; let $rad = 6378137; let $rad1 = parseFloat($geo[1]) * Math.PI / 180.0; let $rad2 = parseFloat($point[1]) * Math.PI / 180.0; let $sub1 = $rad1 - $rad2; let $sub2 = parseFloat($geo[0]) * Math.PI / 180.0 - parseFloat($point[0]) * Math.PI / 180.0; let $sub = (2 * $rad * Math.asin(Math.sqrt(Math.pow(Math.sin($sub1 / 2), 2) + Math.cos($rad1) * Math.cos($rad2) * Math.pow(Math.sin($sub2 / 2), 2)))).toFixed(0); return parseInt($sub); } }) } |
我在get函数中会直接跑到step2,然后才到return parseInt($sub)
4 回复
我理解是这样的。 wx.getLocation 这个接口本身执行并不是异步的,同步执行的返回undefined,也不会返回Promise对象。获取地理位置是异步的,体现在 success 的回调里面。 一楼的写法是可以的。附赠 阮一峰es6 入门 await 说明 await
await wx.getLocation这个有问题:
https://developers.weixin.qq.com/community/develop/article/doc/00028cbc2e04e0ddf549d535351c13