异步流程控制

1.串行有关联

一个请求结束后,再发送下一个请求,第二次请求的参数依赖第一请求的返回值。
所用时间为两次请求时间之和。

axios({
  url:'/api/home',
}).then(
  res=>axios({
    url:'/api/follow',
    params:{msg:res.data.msg}  //res为第一次请求的返回值
  }).then(
    res=>console.log('follow',res.data)
  )
)
//避免上述代码的回调地狱,可采用下面的写法
axios({
  url:'/api/home',
}).then(
  res=>axios({
    url:'/api/follow',
    params:{msg:res.data.msg}
  })
).then(
  res=>console.log('follow',res.data)
)
//使用同步书写的思路解决异步问题,async await
async mounted(){
	let result = await axios({url:'/api/home'})
	let result2 = await axios({url:'/api/follow',params:{msg:result.data.msg})
	console.log(2,result2);
}
2.并行无关联

所有请求一起发生,组件有多次求取,会有多次渲染
时间为所有请求中用时最多的一次请求的时间

//请求1
axios({
  url:'/api/home',
}).then(
  res=>this.home=res.data.data
)
//请求2
axios({
  url:'/api/follow',
}).then(
  res=>this.follow=res.data.data
)
//用promise.all /axios.all解决多次渲染问题
Promise.all([
axios({url:'/api/home'}),
axios({url:'/api/follow'})
]).then(
  res=>{//res为一个数组,索引顺序对应请求顺序
    this.home = res[0].data.data
    this.follow = res[1].data.data
  }
) 
axios.all([
  axios({url:'/api/home'}), 
  axios({url:'/api/follow'})
]).then(axios.spread((home, follow)=>{//按照发送请求顺序,约定每次请求回来得数据的名字
   this.home=home.data.data;//通过名字访问数据
   this.follow=follow.data.data;
}))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值