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
}
