Vuex結合 async/await 優雅的管理接口請求


先看看 async/await 的語法

async 函數返回一個 Promise 對象

async 函數內部 return 返回的值。會成為 then 方法回調函數的參數。

async function  f() {
    return 'hello world'
};
f().then( (v) => console.log(v)) // hello world

如果 async 函數內部拋出異常,則會導致返回的 Promise 對象狀態變為 reject 狀態。拋出的錯誤而會被 catch 方法回調函數接收到。

async function e(){
    throw new Error('error');
}
e().then(v => console.log(v))
.catch( e => console.log(e));

async 函數返回的 Promise 對象,必須等到內部所有的 await 命令的 Promise 對象執行完,才會發生狀態改變

也就是說,只有當 async 函數內部的異步操作都執行完,才會執行 then 方法的回調。

const delay = timeout => new Promise(resolve=> setTimeout(resolve, timeout));
async function f(){
    await delay(1000);
    await delay(2000);
    await delay(3000);
    return 'done';
}
f().then(v => console.log(v)); // 等待6s后才輸出 'done'

正常情況下,await 命令后面跟着的是 Promise ,如果不是的話,也會被轉換成一個 立即 resolvePromise
如下面這個例子:

async function  f() {
    return await 1
};
f().then( (v) => console.log(v)) // 1

如果返回的是 reject 的狀態,則會被 catch 方法捕獲。

Async 函數的錯誤處理

async 函數的語法不難,難在錯誤處理上。
先來看下面的例子:

let a;
async function f() {
    await Promise.reject('error');
    a = await 1; // 這段 await 並沒有執行
}
f().then(v => console.log(a));

如上面所示,當 async 函數中只要一個 await 出現 reject 狀態,則后面的 await 都不會被執行。
解決辦法:可以添加 try/catch

// 正確的寫法
let a;
async function correct() {
    try {
        await Promise.reject('error')
    } catch (error) {
        console.log(error);
    }
    a = await 1;
    return a;
}

correct().then(v => console.log(a)); // 1

如果有多個 await 則可以將其都放在 try/catch 中。

如何在項目中使用呢  讓我們結合Vuex來試試:

如何引入Vuex  以及編寫 

stroe.js

// stroe.js
import Vue from 'vue' import Vuex from 'vuex' import actions from './actions' Vue.use(Vuex) export const name = 'contract' const state = { // 數據字典 initData: [], number: '' } const mutations = { // 獲取數據字典 SET_INIT_DATA (_state, obj) { _state.initData = obj }, // 獲取分單申請ID集合 SET_NUMBER(_state, data) { _state.number = data console.log(_state) } } // 向外暴露store 對象 const store = new Vuex.Store({ namespaced: true, name, state, actions, mutations, }) // 模塊動態注冊 項目龐大接口數量很大是便於管理 有疑惑 直戳 https://vuex.vuejs.org/zh/guide/modules.html 去vuex官網看看解釋的更詳細 store.registerModule(name, { namespaced: true, name, state, actions, mutations, }) export default store

actions.js 文件

// actions.js
import axios from 'axios'; const ajax = { // 獲取數據字典 GET_INIT_DATA: `agreement/init?`, // 獲取編號 GET_CONTRACT_NUMBER: `agreement/archive?`, // 保存基本信息 SUBMIT_INFO: `agreement/submit/basic?` } // 提取公共部分 const API_URL = 'product/v1/middle/'; // 增加前綴 let INTERFACE = {}; for (let key in ajax) { INTERFACE[key] = API_URL + ajax[key]; }
// 獲取編號
function getContractNumber({commit}) {
return new Promise((resolve, reject) => {
axios.get(INTERFACE.GET_CONTRACT_NUMBER).then(data => {
commit('SET_NUMBER', {data}) // 改變state.number
resolve(data.data)
}).catch((err) => {
window.Alert(err)
})
})
}
// 獲取數據字典
async function getInitData({commit, state}, params) {
 const num = await getContractNumber()
return new Promise((resolve, reject) => { axios.get(INTERFACE.GET_INIT_DATA).then((data) => {
    commit('SET_INIT_DATA', {data}) // 改變state.initData resolve(data.data) }).
catch((err) => { window.Alert(err) // 全局錯誤提示 }) }) }
// 獲取詳情 function getInfo(id) {
return new Promise((resolve, reject) => {
// 寫法2 模板字符串語法 axios.
get(`apply/v1/${id}/input?`).then(data => { resolve(data.data) }).catch((err) => { window.Alert(err) // 全局錯誤提示 }) }) }
// 提交
async function onSubmit({commit}, params) { const result = await getInfo() console.log(result) return new Promise((resolve, reject) => { axios.post(`${INTERFACE.SUBMIT_INFO}/${result.num}/products`, {...params}).then(data => { resolve(data) }).catch((err) => { window.Alert(err) // 全局錯誤提示 }) }) } export default { saveContrantInfo, getContractNumber, getInitData, getInfo, onSubmit }

 index.vue文件調用

<script> import { name as moduleName } from '@/store'
  export default {
    data() {
      return {
    // 基本信息
contractInfo: {},
    // 數據字典
    baseData: [] } }, created() { // 獲取基本信息 若要then有返回值 actions 必須 resolve() 不然 then 方法沒用 this.$store.dispatch(`${moduleName}/getInfo`).then(data => { console.log(data) }) // 獲取數據字典 this.$store.dispatch(`${moduleName}/getInitData`).then(data => { Object.assign(this.baseData, data) }) }, methods: { // 獲取編號 async getNumber() {
     // 在 actions 函數里 await 也行 看具體需求 此例只作為演示 await 調用
const obj = await this.$store.dispatch(`${moduleName}/getContractNumber`) this.contractInfo.fileNo = obj.fileNo },// 提交 submit() { this.$store.dispatch(`${moduleName}/onSubmit`, this.contractInfo).then(data => { console.log(data) }) } } } </script>

以上就是 vuex 結合 async/await 的簡單應用事例了。歡迎指正不足不對之處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM