1. 程式人生 > 其它 >JavaScript 等待非同步請求資料返回值後,繼續執行程式碼 —— async await Promise的使用方法

JavaScript 等待非同步請求資料返回值後,繼續執行程式碼 —— async await Promise的使用方法

技術標籤:JavaScript

需求

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