zl程序教程

您现在的位置是:首页 >  前端

当前栏目

vue实现循环发起多个异步请求——Promise.all()与Promise.race()

Vue循环异步 实现 请求 多个 all Promise
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()没有先后顺序,那个先请求回来那个先显示