JavaScript 等待异步请求数据返回值后,继续执行代码 —— async await Promise的使用方法

需求

1. 访问百度地图API 获取指定行政区划的坐标 

2. 根据行政区划的坐标,在百度地图上标注行政区划的名称

代码范例 (以在.vue文件中使用为例)

mounted(){
    // 调用方法——在百度地图上标注行政区划的名称
    this.addRegionLabel('武汉市', '青山区')
},
  •  在异步返回数据的方法前加 await
  • 在内部存在 await 的方法前加 async
// 添加行政区划文本标注
async addRegionLabel(city, region) {
    let point = await this.getReigonLocation(city, region)
    // 创建文本标注对象
    let label = new BMap.Label(region, {position: new BMap.Point(point.lng, point.lat)});
    // 在地图上添加文本标注对象
    this.map.addOverlay(label);
},

 在异步返回数据的方法中

  1.  直接 return 异步请求
  2.  在 .then 中,使用 return Promise.resolve( res.data); 返回异步请求返回值中需要的数据(res.data指代要返回的数据)
// 获取行政区划的坐标
getReigonLocation(city, region) {
    return this.$http.get("/baiduMapAPI/place/v2/search", {
        params: {
            query: region,
            region: city,
            output: 'json',
            city_limit: true,
            ak: this.GLOBAL.baiduMapAK
        }
    }).then(res => {
        let location = res.data.results[0].location
        return Promise.resolve(location);
    })
},

猜你喜欢

转载自blog.csdn.net/weixin_41192489/article/details/113094660