vue实现循环发起多个异步请求——Promise.all()与Promise.race()
2023-09-27 14:27:29 时间
直接先上个例子
<template>
<div>
<h1>page1</h1>
<p>{{ msg }}</p>
<el-button type="primary" plain @click="downloadList()">主要按钮</el-button>
</div>
</template>
<script>
export default {
data() {
return {
msg: "我是page1组件",
pagnation:{
total:1000,
}
}
},
methods: {
downloadList(num) {
let array = []
// 计算可以循环多少次
let n = 1
if (this.pagnation.total < 100) {
n = 1
} else {
n = Math.ceil(this.pagnation.total / 100)
}
for (let i = 0; i < n; i++) {
array = array.concat(this.ForPromise(i))
}
Promise.all(array).then((res) => {
console.log(res) // [ 0, 1, 2 ]
})
},
ForPromise(num) {
return new Promise((resolve, reject) => {
resolve('成功了'+num);
//请求操作
// this.axios.get('http://test.fastadmin.cn/index.php/api/index/test',{}).then(res => {}).catch(err => {});
})
},
sleep(ms) { //sleep延迟方法2
var unixtime_ms = new Date().getTime();
while (new Date().getTime() < unixtime_ms + ms) { }
},
}
}
</script>
结果
说明
Promise.all 在任意一个传入的 promise 失败时返回失败。例如,如果你传入的 promise中,有四个 promise
在一定的时间之后调用成功函数,有一个立即调用失败函数,那么 Promise.all 将立即变为失败。
Promise.race()的使用
var p1 = new Promise(function(resolve, reject) {
setTimeout(resolve, 500, "one");
});
var p2 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, "two");
});
Promise.race([p1, p2]).then(function(value) {
console.log(value); // "two"
// 两个都完成,但 p2 更快
});
3.Promise.all()与Promise.race()请求时的区别
Promise.all() 适合于后面的异步请求接口依赖前面的接口请求的数据时使用。
Promise.race()没有先后顺序,那个先请求回来那个先显示
相关文章
- 精品微信小程序ssm户外体能训练教学平台+后台管理系统|前后分离VUE
- Vue简单使用
- 【Vue】基于nodejs的vue项目打包编译部署
- vux+vuex+vue+Es6开发微信公众号的坑
- vue系列:如何用axios提交键值相同的参数
- Vue中的动态路由匹配路由问题
- VUE系列一:VUE入门:搭建脚手架CLI(新建自己的一个VUE项目)
- vue 实现简单的待办事项,记事本功能
- SpringBoot+Vue(一)商品管理系统 模式介绍 、项目改造
- 手写Vue组件踩坑与心得
- Vue.js 系列教程 3:Vue-cli,生命周期钩子
- vue——封装axios,统一设置超时时间,再针对个别请求设置不同的超时时间
- vue——请求跨域时,vcli2/vcli3设置代理
- 前端学习之VUE基础一:什么是Vue、指令、事件/样式/属性绑定、分支/循环结构