1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > JavaScript 等待异步请求数据返回值后 继续执行代码 —— async await Promise的使用方法

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

时间:2020-07-14 16:41:32

相关推荐

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

在异步返回数据的方法中

直接 return 异步请求在 .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].locationreturn Promise.resolve(location);})},

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。