1. 程式人生 > 實用技巧 >async與await使用

async與await使用

自己總結的:

1、讓非同步的程式碼可以使用同步的方式,邏輯更加清晰,優雅

2、重點:基於promise使用

模擬場景:呼叫A介面的同時返回資料後在次呼叫B介面獲取資料

export default {
  async created () {
    // 使用 promise 方式
    // 呼叫A
    // this.$http.get('http://localhost:3000/a').then(res => {
    //   console.log(res.data)
    //   // 呼叫B
    //   return this.$http.get('http://localhost:3000/b')
    
// }).then(res => { // console.log(res.data) // }) // 函式的返回值 載入await之後 是then接受的資料 // 在使用await之後在 外層函式必須用async 來申明 const resA = await this.$http.get('http://localhost:3000/a') const resB = await this.$http.get('http://localhost:3000/b') console.log(resA.data, resB.data) }

總結:

  • awiat 修飾返回promise物件的函式,結果:得到成功後的資料。

  • awiat 使用只能在async修飾的函式內,在awiat的外層函式加上async關鍵字。

  • awiat 修飾的函式 只會阻礙程式執行的,async關鍵字修飾函式 非同步函式。