axios执行同步
**axios:**是一种异步请求的方式 ,通过回调函数的方式在请求中做的更多的是可控的功能,
简单介绍一下axios,有疑问的可以看我的博客里边有axios的详细介绍,以及一些个应用场景!!!
https://blog.csdn.net/yhr0322/article/details/101977534
axios同步之async-----await
在某些特定的时候 也会用到axios同步 虽然异步大大提高了效率,但实际也会有一些时候需要同步,那该如何解决呢?
这个时候就可以用到async–await了
小编还特意写了一个实列 大家一起来看看吧!!!
使用场景以及需求
1.需要在页面渲染时通过created生命周期用axios请求数据,并将数据赋值给一个变量,
2.在变量接收完成后,对变量进行过滤筛选出我想要的数据
必须在页面渲染前完成以上两个需求
created () {
//pending - 等待 用封装的axios请求数据
_product.bbbb_list().then(res => {
//数据请求成功后进行赋值
this.$store.state.bbbb_list = res.data.data
})
//console控制台输出变量
console.log( this.$store.state.bbbb_list)
//对刚刚接收的变量进行过滤 拿到想要的数据
this.$store.state.bbbb_lista =this.$store.state.bbbb_list.filter((item)=>{
if(item.type.charAt(item.type.length-1)!=2){
//console控制台输出item.name
console.log(item.name)
return item
}
})
},
以上的输出结果中只有 console.log( this.$store.state.bbbb_list)
而下边的没有输出结果 就是因为axios是异步的请求方式
改正为同步时
async created () {
//通过async结合await使用
let res = await axios.post('https://api.it120.cc/small4/shop/goods/category/all')
//这里的res就是你axios请求回来的结果了
this.$store.state.bbbb_list = res.data.data
//console控制台输出变量
console.log( this.$store.state.bbbb_list)
对刚刚接收的变量进行过滤 拿到想要的数据
this.$store.state.bbbb_lista =this.$store.state.bbbb_list.filter((item)=>{
if(item.type.charAt(item.type.length-1)!=2){
//console控制台输出item.name
console.log(item.name)
return item
}
})
},
以上的输出结果为 ****console.log( this.$store.state.bbbb_list)***和 console.log(item.name)
当然了 解决的方法有很多,希望小编拾伍的笔记可以帮到大家,如果你有更好的方法,请留言告诉我!!!大家一起进步,一起学习!!!欢迎点赞留言,谢谢!!!