axios如何执行同步----async

axios执行同步

**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)

当然了 解决的方法有很多,希望小编拾伍的笔记可以帮到大家,如果你有更好的方法,请留言告诉我!!!大家一起进步,一起学习!!!欢迎点赞留言,谢谢!!!

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值