SoFunction
Updated on 2025-04-06

Methods to encapsulate axios using async await

es6's promise gradually solved the problem of layered callbacks. es8's async await has turned async into a synchronous writing method. In vue, axios can be encapsulated so that all requests can use synchronous writing method, and error information can be processed at the same time. A file can be created and API instances can be created globally.

import axios from 'axios'
const qs = require('qs')
const api = {
 async get (url, data) {
  try {
   let res = await (url, {params: data})
   res = 
   return new Promise((resolve) => {
    if ( === 0) {
     resolve(res)
    } else {
     resolve(res)
    }
   })
  } catch (err) {
   alert('The server error')
   (err)
  }
 },
 async post (url, data) {
  try {
   let res = await (url, (data))
   res = 
   return new Promise((resolve, reject) => {
    if ( === 0) {
     resolve(res)
    } else {
     reject(res)
    }
   })
  } catch (err) {
   // return ()
   alert('The server error')
   (err)
  }
 },
}
export { api }

In the above code, try and catch are first used to capture the request error. If the network status is poor, server error, etc., then in the successful request state, the request code can also be processed uniformly. This can be processed according to the specific project. The above example shows that when code=0 is the correct state.

You can refer to the following for use, taking the vue project as an example:

import { api } from 'common/js/api'

export default {
 data () {
  return {
   list: [],
  }
 },
 created () {
  ()
 },
 methods: {
  async getList () {
   let {data} = await ('/ferring/test/list')
   (data)
    = data
  }
 },
}

Sometimes we may think that error handling can be popped through some components of vue such as toast, but this is not in the project, so how should we use it? Here is a brief description of the vue project as an example:

Some ui libraries, such as element ui, have made toast into plug-ins, and you can directly use this example to open pop-up windows.

<template>
 <el-button type="text" @click="open">Click to open Message Box</el-button>
</template>

<script>
 export default {
  methods: {
   open() {
    this.$alert('This is a paragraph', 'Title name', {
     confirmButtonText: 'Sure',
     callback: action => {
      this.$message({
       type: 'info',
       message: `action: ${ action }`
      });
     }
    });
   }
  }
 }
</script>

The above code is excerpted from element Ui. If you want to handle it globally, how to get this example of vue? In it, you can mount the vue instance on a window object.

/* eslint-disable no-new */
 = new Vue({
 el: '#app',
 router,
 render: h => h(App),
})

Then go back to the just now, you can call .$alert directly in the case of resolve or catch, so that you can use the plug-in form of vue to call the pop-up component.

If there is no such pop-up component called with this, we can also write one and then control it globally through vuex.

Then you can introduce store

import store from '../store'

Under catch or resolve conditions

('showDialog',{true,'The request error'})

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.