Public account: wechat search front end tool person; Take more dry goods

Introduce a,

  1. Unified management of requests is an indispensable part of every project;
  2. The article was written a little long ago2018Years of writing; In view of thevue2.xGrammar;
  3. A new version ofvue3.x + vuexSyntax jumps to previous articlesJuejin. Cn/post / 688786…;
  4. Recently, the blog park has been gradually moved over, so there is not much new stuff…
  5. Such asVue3. X, Flutter, SSR, Node, data visualizationCan view the previous article;
  6. Recently, the original project is using a micro front endqiankunRefactoring (vue3+TSUmi3.x+react16+TS); Hit the pit… ; Share it later

Second, the async/await

Let’s look at the async/await syntax

The async function returns a Promise object

The value returned by the async function’s return. Becomes an argument to the then method callback function.

async function fn() {

    return 'hello world'

};

fn().then( res => console.log(res))

// hello world

Copy the code

If an exception is thrown inside the async function, the state of the returned Promise object changes to Reject.

An error thrown is received by the catch method callback.

async function fn() {

    throw new Error('error');

}

fn()

  .then(res => console.log(resd))

  .catch( err => console.log(err));

Copy the code

The state of the Promise returned by async functions will not change until all the Promise objects of the internal await command have been executed

That is, the callback to the then method is executed only when all asynchronous operations inside an async function have been executed.

const delay = timeout => new Promise(resolve=> setTimeout(resolve, timeout));

async function fn() {

    await delay(1000);

    await delay(2000);

    await delay(3000);

    return 'done';

}

fn().then(res => console.log(res));

// Wait for 6s before output'done'

Copy the code

Normally, the await command is followed by a Promise, and if it is not, it is converted to an immediately resolve Promise as in this example:

async function  fn() {

    return await 1

};

fn().then( res => console.log(res))

/ / 1

Copy the code

If a reject state is returned, it is caught by the catch method.

Error handling of Async functions

The syntax of async functions is not difficult, but the difficulty lies in error handling. Let’s start with the following example:

let a;

async function fn() {

    await Promise.reject('error');

a = await 1; // This "await" is not executed

}

fn().then(res => console.log(res));

Copy the code

As shown above, when an async function is await with a reject state, the following await will not be executed. Solution: Add a try/catch.

// The correct way to write

let a;

async function correct() {

    try {

        await Promise.reject('error')

    } catch (error) {

        console.log(error);

    }

    a = await 1;

    return a;

}



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

Copy the code

If you have more than one await, you can put them all in a try/catch.

3. Vuex is integrated into the project

How to introduce and write 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 = {

// Data dictionary

  initData: [],

  number: ' '

}



const mutations = {

// Get the data dictionary

  SET_INIT_DATA (_state, obj) {

    _state.initData = obj

  },

// Get the ID set

  SET_NUMBER(_state, data) {

    _state.number = data

    console.log(_state)

  }

}



// Expose the store object

const store = new Vuex.Store({

  namespaced: true.

  name,

  state,

  actions,

  mutations,

})



/ / dynamic registered a high number of large projects interface module is to facilitate management have doubts directly https://vuex.vuejs.org/zh/guide/modules.html vuex website see explain in more detail

store.registerModule(name, {

  namespaced: true.

  name,

  state,

  actions,

  mutations,

})



export default store

Copy the code

Actions. Js file

// actions.js

import axios from 'axios';



const ajax = {

// Get the data dictionary

GET_INIT_DATA: `agreement/init? `,

// Get the number

GET_CONTRACT_NUMBER: `agreement/archive? `,

// Save basic information

SUBMIT_INFO: `agreement/submit/basic? `

}

// Extract the public part

const API_URL = 'product/v1/middle/';



// Add the prefix

let INTERFACE = {};

for (let key in ajax) {

  INTERFACE[key] = API_URL + ajax[key];

}



// Get the number

function getContractNumber({commit}) {

  return new Promise((resolve, reject) => {

    axios.get(INTERFACE.GET_CONTRACT_NUMBER).then(data => {

      commit('SET_NUMBER', {data}) // Change state.number

      resolve(data.data)

    }).catch((err) => {

      window.Alert(err)

    })

  })

}

// Get the data dictionary

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}) // Change state.initdata

      resolve(data.data)

    }).catch((err) => {

Window. Alert(err) // Global error message

    })

  })

}



// Get details

function getInfo(id) {

  return new Promise((resolve, reject) => {

// Write 2 template string syntax

    axios.get(`apply/v1/${id}/input? `).then(data => {

      resolve(data.data)

    }).catch((err) => {

Window. Alert(err) // Global error message

    })

  })

}



/ / submit

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) // Global error message

    })

  })

}



export default {

  saveContrantInfo,

  getContractNumber,

  getInitData,

  getInfo,

  onSubmit

}

Copy the code

The index.vue file is called

<script>

  import { name as moduleName } from '@/store'

  export default {

    data() {

      return {

// Basic information

ContractInfo: {},

// Data dictionary

         baseData: []

      }

    },

    created() {

// Get basic information if necessarythenActions must resolve() otherwisethenMethods use

      this.$store.dispatch(`${moduleName}/getInfo`).then(data => {

        console.log(data)

      })

// Get the data dictionary

      this.$store.dispatch(`${moduleName}/getInitData`).then(data => {

        Object.assign(this.baseData, data)

      })

    },

    methods: {

// Get the number

      async getNumber() {

// Call 'await' in actions as an example

        const obj = await this.$store.dispatch(`${moduleName}/getContractNumber`)

        this.contractInfo.fileNo = obj.fileNo

      },

/ / submit

      submit() {

        this.$store.dispatch(`${moduleName}/onSubmit`, this.contractInfo).then(data => {

          console.log(data)

        })

      }

    }

  }

</script>

Copy the code

Fourth, the end

Article source: your blog at https://www.cnblogs.com/ljx20180807/p/9838259.html