vue async/await同步 案例

1.async/await場景前端

這是一個用同步的思惟來解決異步問題的方案,當前端接口調用須要等到接口返回值之後渲染頁面時。vue

2.名詞解釋node

  >asyncios

    async的用法,它做爲一個關鍵字放到函數前面,用於表示函數是一個異步函數,由於async就是異步的意思, 異步函數也就意味着該函數的執行不會阻塞後面代碼的執行,async 函數返回的是一個promise 對象。axios

 >await後端

   await的含義爲等待。意思就是代碼須要等待await後面的函數運行完而且有了返回結果以後,才繼續執行下面的代碼。這正是同步的效果api

 >例子promise

  

function fn() { 
 
    return new Promise((resolve, reject) => { 
 
        setTimeout(() => { 
 
            reject(hello vue.js'); 
 
        }, 1000); 
 
    }) 
 
} 
 
  
 
const foo = async () => { 
 
    try { 
 
        await fn(); 
 
    } catch (e) { 
 
        console.log(e);  // some error 
 
    } 
 
} 

 

3.案例服務器

  auth.vue網絡

  須要注意:await必須放在async中 

  import http from '../../utils/http'
  import api from '../../utils/api'

   methods: {
      fetchData: async function () {
        var that = this
        var code = Store.fetchYqm();
        let params = {
          inviteCode: code
        }
        const response = await http.post(params,api.getCode)
         var resJson = response.data;
        
      }
}

http.js

'use strict'

import axios from 'axios'
import qs from 'qs'

axios.interceptors.request.use(config => {
  // loading
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})

function checkStatus (response) {
  // loading
  // 若是http狀態碼正常,則直接返回數據
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    return response
    // 若是不須要除了data以外的數據,能夠直接 return response.data
  }
  // 異常狀態下,把錯誤信息返回去
  return {
    status: -404,
    msg: '網絡異常'
  }
}

function checkCode (res) {
  // 若是code異常(這裏已經包括網絡錯誤,服務器錯誤,後端拋出的錯誤),能夠彈出一個錯誤提示,告訴用戶
  if (res.status === -404) {
    alert(res.msg)
  }
  if (res.data && (!res.data.success)) {
    alert(res.data.error_msg)
  }
  return res
}

export default {
  post (data,url) {
    return axios({
      method: 'post',
      url: url,
      data: qs.stringify(data),
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    )
  },
  get (url, params) {
    return axios({
      method: 'get',
      baseURL: 'https://cnodejs.org/api/v1',
      url,
      params, // get 請求時帶的參數
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  }
}

api.js

export default {
  getCode: 'http://127.0.0.1:8888/get_author'
}
相關文章
相關標籤/搜索