vue 如何依次请求 20 多个 axios 请求,同步请求多个,按次序请求

什么是同步,什么是异步

反正挺绕,我一直默认理解的是同步就是多个线程同时请求,在软件开发中实则不是这么理解的。
同步是单线程,同一时间只有一个请求
异步是多线程,就是多个请求异步执行,会有多个请求同时进行

异步的时候是这样的,多个请求同时触发,每个请求的结束时间不确定。
在这里插入图片描述

一、需求

有一个人员列表, userListData,每个人员都有多张卡片 + 多个指纹数据

  • 将人员列表中的所有人员的所有卡片+指纹数据都展示出来。
  • 后台因某种条件限制,只提供查询单个人员卡片、单个人员指纹数据的接口。
  • 且后台不能一次性接收多个请求,不然会卡死,能保证的是 300ms 内处理两个请求是没有问题的。

二、如何实现

因为我们用的是 axios,它是异步的,返回每个请求的 promise 对象,而我们需要的是同步功能,就是同一时间,只有一个请求在执行。执行完上面的请求之后,再执行下面的请求。

需要使用 ES6 的 async await

具体使用方法可以看这里:
https://blog.csdn.net/weixin_44972441/article/details/124785718

基本的用法是:

async 的方法内,使用 await 来同步执行返回 promise 的方法,例:

methods: {
	async getAllUserInfo(){
		let user1Info = await getUserInfoOf(1)
		let user2Info = await getUserInfoOf(2)
		console.log(user1Info, user2Info)
	}
}

对比上面的请求,下面这种请求的结果返回顺序是不可控的

methods: {
	getAllUserInfo(){
		getUserInfoOf(1)
			.then(res => {
				console.log(user1Info)
			})
		getUserInfoOf(2)
			.then(res => {
				console.log(user2Info)
			})
	}
}

三、具体实现方法

作一个循环请求用户数据的方法,循环在这个方法内调用自己这个方法,入口处作判断,满足条件:用户已经遍历完成,就结束。

data(){
	return {
            // 用户数据列表
            userListData: [
                // { id: 1, treeId, user2, label: '华强' ] }
            ],
            // 循环请求用户数据时的 标记 index
            loopIndex: 0,
	}
},
methods: {
        treeCheckAll(){
            this.getAllUserInfoWithNoUpdate()
        },
        // 只获取人员数据,不改变其它
        getAllUserInfoWithNoUpdate(){
            let loadingOption = {
                lock: true,
                text: "正在请求所有用户数据,请耐心等待,不要离开该页面...",
                background: "rgba(0, 0, 0, 0.7)"
            }
            this.loopIndex = 0
            this.layerLoadingAllUser = Loading.service(loadingOption)
            this.getUserInfoSync()
        },
        // 连续依次获取所有用户信息
        async getUserInfoSync(){
            // 每次执行之前,判断是否已经遍历所有用户,如果已经遍历所有用户,执行结束
            if (this.loopIndex < this.userListData.length){
                let currentUser = this.userListData[this.loopIndex]

				// 获取卡片信息
				 let res = await doorApi.cardList({
                        doorId: this.doorId,
                        employeeNo: currentUser.id
                    }, this.cancelTokenSource.token)
                    // 加了 await 的方法,它会依次往下执行,不会像原始 axios 那样需要回调方法一样的使用
                    if (res && res.length > 0){
                        currentUser.cards = res
                    } else {
                        currentUser.cards = []
                    }

				// 获取指纹信息
				 let res = await doorApi.fingerprintList({
                        doorId: this.doorId,
                        employeeNo: currentUser.id
                    }, this.cancelTokenSource.token)
                    // 加了 await 的方法,它会依次往下执行,不会像原始 axios 那样需要回调方法一样的使用
                    if (res && res.length > 0){
                        currentUser.fingerprints = res.map(item => item.fingerPrintID)
                    } else {
                        currentUser.fingerprints = []
                    }

                this.loopIndex = this.loopIndex + 1
                // 每 300ms 执行一下此方法
                setTimeout(this.getUserInfoSync, 300)
            } else {
            	// 连续请求结束后的操作
            	// do something
            }
        },
	
}

其请求过程是这样的:

在这里插入图片描述

四、使用递归

还有一种方法使用递归。

比如,我有一个数组 wordsChunks = [ [words], [words]]
我需要将这个数组中的每个数组都上传到服务器。
可以定义几个变量:

currentChunkIndex: 0, // 当前分组 index,批量上传用
wordsChunks: [[word, word,word], [word,word,word]], // 词条分组
addNewWords(wordsChunk){
    wubiApi
        .word
        .addBatch({
            category_id: this.formBatch.category_id,
            words: wordsChunk[this.currentChunkIndex]
        })
        .then(res => {
            this.countExisted += res.data.existCount
            this.countAdded += res.data.addedCount
            this.currentChunkIndex++

            // 以 currentChunkIndex 的值为判断,当大于 分组数时,停止上传
            if (this.currentChunkIndex < this.wordsChunks.length){
                this.addNewWords(this.wordsChunks) // 自己调用自己
            } else {
                this.addNewWordsFinished()
            }
        })
},

在这里插入图片描述
最终的结果如下:

在这里插入图片描述

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐