事由
之前项目遇到一个需求:需要前端调用一个api两万次左右,今天看了之前的代码,优化一波记录一下。
处理方案
把要发送的数据分装到一个数组,循环数组在循环中调用
// 执行器
async actuator(target) {
// 是否执行结束
let endOfSending = true
// 记录起始时间
let beginTime = new Date()
// 执行
for(let i=0; i<target.length && endOfSending; i++) {
endOfSending = false
// 调用API
await Api(this.requestDataNull).then(res => {
// 执行成功
this.handleSuccess(res)
endOfSending = true
}).catch(err => {
// 执行失败
this.handleFail(err)
console.log(err)
endOfSending = true
})
}
// 记录执行用时
let timeUse = new Date() - beginTime
console.log(`执行用时: ${timeUse}ms`)
},
调用就可以多个异步同时去执行
handleClick() {
// 操作目标
let target = []
for(let i=0; i<1000; i++){
target.push(i)
}
// 执行(执行器是异步的 可以同时执行加快执行速度)
this.actuator(target)
this.actuator(target)
this.actuator(target)
this.actuator(target)
this.actuator(target)
},
效果
正常调用并且可以通过成功和失败的处理函数记录进度以及处理响应的业务,现在遇到的问题是进度提示调用完成了,但是浏览器控制台还在继续跑日志。