async/await 还是同步怎么办?
发布于 5 年前 作者 wanxiuying 6514 次浏览 来自 官方Issues
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

因为wx.getLocation本身不是Promise的,所以要用一个Promise包裹才行

let getDistance = (point) => {

    return new Promise((rs, rj)=>{

        wx.getLocation({

            type: “gcj02”,

            altitude: true,

            success: res => {

                let $geo = [res.longitude || 180, res.latitude || -80],

                $pointJson = JSON.stringify(point),

                $pointGeo = JSON.parse($pointJson),

                $point = $pointGeo.coordinates,

                $rad = 6378137,

                $rad1 = parseFloat($geo[1]) * Math.PI / 180.0,

                $rad2 = parseFloat($point[1]) * Math.PI / 180.0,

                $sub1 = $rad1 - $rad2,

                $sub2 = parseFloat($geo[0]) * Math.PI / 180.0 - parseFloat($point[0]) * Math.PI / 180.0,

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

                rs(parseInt($sub))

            },

            fail(err){

                rj(err)

            }

        })

    })

}

官方提供了小程序api promise版本的npm包

回到顶部