vue async/await同步 案例
1. async/await場景
這是一個用同步的思維來解決異步問題的方案,目前端接口調用需要等到接口傳回值以後渲染頁面時。
2. 名詞解釋
async
async的用法,它作為一個關鍵字放到函數前面,用于表示函數是一個異步函數,因為async就是異步的意思, 異步函數也就意味着該函數的執行不會阻塞後面代碼的執行,async 函數傳回的是一個promise 對象。
await
await的含義為等待。意思就是代碼需要等待await後面的函數運作完并且有了傳回結果之後,才繼續執行下面的代碼。這正是同步的效果
例子
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'
}