1. 程式人生 > 程式設計 >vue中用 async/await 來處理非同步操作

vue中用 async/await 來處理非同步操作

昨天看了一篇vue的教程,作者用async/ await來發送非同步請求,從服務端獲取資料,程式碼很簡潔,同時async/await 已經被標準化,也是需要學習一下了。

先說一下async的用法,它作為一個關鍵字放到函式前面,

async function timeout() {
  return 'hello world';
}

只有一個作用,它的呼叫會返回一個promise 物件。呼叫一下看看就知道了,怎麼呼叫?async 函式也是函式,所以它的呼叫和普通函式的呼叫沒有什麼區別,直接加括號呼叫就可以了,為了看結果,console.log 一下

async function timeout() {
  return 'hello world'
}
console.log(timeout());

看一下控制檯

vue中用 async/await 來處理非同步操作

async函式(timeout)的呼叫,確實返回promise 物件,並且Promise 還有status和value,如果async 函式中有返回值,當呼叫該函式時,內部會呼叫Promise.solve() 方法把它轉化成一個promise 物件作為返回,但如果timeout 函式內部丟擲錯誤呢?

async function timeout() {
  throw new Error('rejected');
}
console.log(timeout());

就會呼叫Promise.reject() 返回一個promise 物件,

vue中用 async/await 來處理非同步操作

那麼要想獲取到async 函式的執行結果,就要呼叫promise的then 或catch 來給它註冊回撥函式,

async function timeout() {
  return 'hello world'
}
timeout().then(result => {
  console.log(result);
})

如果async 函式執行完,返回的promise 沒有註冊回撥函式,比如函式內部做了一次for 迴圈,你會發現函式的呼叫,就是執行了函式體,和普通函式沒有區別,唯一的區別就是函式執行完會返回一個promise 物件。

async function timeout() {
  for (let index = 0; index < 3; index++) {
    console.log('async '+ index);
  }
}
console.log(timeout());
console.log('outer')

async 關鍵字差不多了,最重要的就是async函式的執行會返回一個promise 物件,並且把內部的值進行promise的封裝。如果promise物件通過then或catch方法又註冊了回撥函式,async函式執行完以後,註冊的回撥函式就會放到非同步佇列中,等待執行。如果只是async,和promise 差不多,但有了await就不一樣了, await 關鍵字只能放到async 函式裡面,await是等待的意思,那麼它等待什麼呢,它後面跟著什麼呢?其實它後面可以放任何表示式,不過我們更多的是放一個返回promise 物件的表示式,它等待的是promise 物件的執行完畢,並返回結果

現在寫一個函式,讓它返回promise 物件,該函式的作用是2s 之後讓數值乘以2

// 2s 之後返回雙倍的值
function doubleAfter2seconds(num) {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve(2 * num)
    },2000);
  } )
}

現在再寫一個async 函式,從而可以使用await 關鍵字, await 後面放置的就是返回promise物件的一個表示式,所以它後面可以寫上 doubleAfter2seconds 函式的呼叫

async function testResult() {
  let result = await doubleAfter2seconds(30);
  console.log(result);
}

現在呼叫testResult 函式

testResult();   

開啟控制檯,2s 之後,輸出了60.

現在看看程式碼的執行過程,呼叫testResult 函式,它裡面遇到了await,await 表示等待,程式碼就暫停到這裡,不再向下執行了,它等待後面的promise物件執行完畢,然後拿到promise resolve 的值並進行返回,返回值拿到之後,它繼續向下執行。具體到 我們的程式碼,遇到await 之後,程式碼就暫停執行了, 等待doubleAfter2seconds(30) 執行完畢,doubleAfter2seconds(30) 返回的promise 開始執行,2秒 之後,promise resolve 了, 並返回了值為60, 這時await 才拿到返回值60, 然後賦值給result, 暫停結束,程式碼繼續執行,執行 console.log語句。

就這一個函式,我們可能看不出async/await 的作用,如果我們要計算3個數的值,然後把得到的值進行輸出呢?

async function testResult() {
  let first = await doubleAfter2seconds(30);
  let second = await doubleAfter2seconds(50);
  let third = await doubleAfter2seconds(30);
  console.log(first + second + third);
}

6秒後,控制檯輸出220,我們可以看到,寫非同步程式碼就像寫同步程式碼一樣了,再也沒有回撥地域了。

這裡強調一下等待,當js引擎在等待promise resolve 的時候,它並沒有真正的暫停工作,它可以處理其它的一些事情,如果我們在testResult函式的呼叫後面,console.log 一下,你發現 後面console.log的程式碼先執行。

async function testResult() {
  let first = await doubleAfter2seconds(30);
  let second = await doubleAfter2seconds(50);
  let third = await doubleAfter2seconds(30);
  console.log(first + second + third);
}

testResult();
console.log('先執行');

再寫一個真實的例子,我原來做過一個小功能,話費充值,當用戶輸入電話號碼後,先查詢這個電話號碼所在的省和市,然後再根據省和市,找到可能充值的面值,進行展示。

為了模擬一下後端介面,我們新建一個node 專案。 新建一個資料夾 async,然後npm init -y 新建package.json檔案,npm install express --save 安裝後端依賴,再新建server.js 檔案作為服務端程式碼, public資料夾作為靜態檔案的放置位置, 在public 資料夾裡面放index.html 檔案, 整個目錄如下

vue中用 async/await 來處理非同步操作

server.js 檔案如下,建立最簡單的web 伺服器

const express = require('express');
const app = express();// express.static 提供靜態檔案,就是html,css,js 檔案
app.use(express.static('public'));

app.listen(3000,() => {
  console.log('server start');
})

再寫index.html 檔案,我在這裡用了vue構建頁面,用axios 傳送ajax請求, 為了簡單,用cdn 引入它們。 html部分很簡單,一個輸入框,讓使用者輸入手機號,一個充值金額的展示區域, js部分,按照vue 的要求搭建了模版

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Async/await</title>
  <!-- CDN 引入vue 和 axios -->
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
  <div id="app">

    <!-- 輸入框區域 -->
    <div style="height:50px">
      <input type="text" placeholder="請輸入電話號碼" v-model="phoneNum">
      <button @click="getFaceResult">確定</button>
    </div>

    <!-- 充值面值 顯示區域 -->
    <div>
      充值面值:
      <span v-for="item in faceList" :key='item'>
        {{item}}
      </span>
    </div>
  </div>

  <!-- js 程式碼區域 -->
  <script>
    new Vue({
      el: '#app',data: {
        phoneNum: '12345',faceList: ["20元","30元","50元"]
      },methods: {
        getFaceResult() {

        }
      }
    })
  </script>
</body>
</html>

為了得到使用者輸入的手機號,給input 輸入框新增v-model指令,繫結phoneNum變數。展示區域則是 繫結到faceList 陣列,v-for 指令進行展示, 這時命令列nodemon server 啟動伺服器,如果你沒有安裝nodemon, 可以npm install -g nodemon 安裝它。啟動成功後,在瀏覽器中輸入 http://localhost:3000,可以看到頁面如下, 展示正確

vue中用 async/await 來處理非同步操作

現在我們來動態獲取充值面值。當點選確定按鈕時, 我們首先要根據手機號得到省和市,所以寫一個方法來發送請求獲取省和市,方法命名為getLocation,接受一個引數phoneNum,後臺介面名為phoneLocation,當獲取到城市位置以後,我們再發送請求獲取充值面值,所以還要再寫一個方法getFaceList,它接受兩個引數,province 和city,後臺介面為faceList,在methods 下面新增這兩個方法getLocation,getFaceList

methods: {
      //獲取到城市資訊
      getLocation(phoneNum) {
        return axios.post('phoneLocation',{
          phoneNum
        })
      },// 獲取面值
      getFaceList(province,city) {
        return axios.post('/faceList',{
          province,city
        })
      },// 點選確定按鈕時,獲取面值列表
      getFaceResult () {
        
      }
    }

現在再把兩個後臺介面寫好,為了演示,寫的非常簡單,沒有進行任何的驗證,只是返回前端所需要的資料。Express 寫這種簡單的介面還是非常方便的,在app.use 和app.listen 之間新增如下程式碼

// 電話號碼返回省和市,為了模擬延遲,使用了setTimeout
app.post('/phoneLocation',(req,res) => {
  setTimeout(() => {
    res.json({
      success: true,obj: {
        province: '廣東',city: '深圳'
      }
    })
  },1000);
})

// 返回面值列表
app.post('/faceList',res) => {
  setTimeout(() => {
    res.json(
      {
        success: true,obj:['20元','30元','50元']
      }
      
    )
  },1000);
})

最後是前端頁面中的click 事件的getFaceResult,由於axios 返回的是promise 物件,我們使用then 的鏈式寫法,先呼叫getLocation方法,在其then方法中獲取省和市,然後再在裡面呼叫getFaceList,再在getFaceList 的then方法獲取面值列表,

     // 點選確定按鈕時,獲取面值列表
      getFaceResult () {
        this.getLocation(this.phoneNum)
          .then(res => {
            if (res.status === 200 && res.data.success) {
              let province = res.data.obj.province;
              let city = res.data.obj.city;

              this.getFaceList(province,city)
                .then(res => {
                  if(res.status === 200 && res.data.success) {
                    this.faceList = res.data.obj
                  }
                })
            }
          })
          .catch(err => {
            console.log(err)
          })
      }

現在點選確定按鈕,可以看到頁面中輸出了 從後臺返回的面值列表。這時你看到了then 的鏈式寫法,有一點回調地域的感覺。現在我們在有async/ await 來改造一下。

首先把 getFaceResult 轉化成一個async 函式,就是在其前面加async, 因為它的呼叫方法和普通函式的呼叫方法是一致,所以沒有什麼問題。然後就把 getLocation 和

getFaceList 放到await 後面,等待執行, getFaceResult 函式修改如下

      // 點選確定按鈕時,獲取面值列表
      async getFaceResult () {
        let location = await this.getLocation(this.phoneNum);
        if (location.data.success) {
          let province = location.data.obj.province;
          let city = location.data.obj.city;
          let result = await this.getFaceList(province,city);
          if (result.data.success) {
            this.faceList = result.data.obj;
          }
        }
      }

現在程式碼的書寫方式,就像寫同步程式碼一樣,沒有回撥的感覺,非常舒服。

現在就還差一點需要說明,那就是怎麼處理異常,如果請求發生異常,怎麼處理? 它用的是try/catch 來捕獲異常,把await 放到 try 中進行執行,如有異常,就使用catch 進行處理。

      async getFaceResult () {
        try {
          let location = await this.getLocation(this.phoneNum);
          if (location.data.success) {
            let province = location.data.obj.province;
            let city = location.data.obj.city;
            let result = await this.getFaceList(province,city);
            if (result.data.success) {
              this.faceList = result.data.obj;
            }
          }
        } catch(err) {
          console.log(err);
        }
      }

現在把伺服器停掉,可以看到控制檯中輸出net Erorr,整個程式正常執行。

以上這篇vue中用 async/await 來處理非同步操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。