模拟循环批量请求后台接口

发布时间 2023-04-07 18:19:27作者: BigJor

使用async, await处理异步请求。用Promise, setTimeout函数模拟后台接口

<!DOCTYPE html>
<html>
<script type="text/javascript">
var arr=[];
var batchSize = 10;
for(i=0;i<30;i++){ arr.push(i);}
function b(startIdx, endIdx){
	return new Promise((resolve, reject)=> {
		setTimeout(()=>{
			let arrexc = arr.slice(startIdx, endIdx);
			for(j = 0; j< arrexc.length; j++){
				console.log("exec", arrexc[j]);
			}
			console.log("called a service:" + new Date().getTime());
			resolve("ok");
		
		}, 1000);
	});
	//return "called a service no promise";
}

async function a(){

	let startIdx = 0;
	let endIdx = startIdx + batchSize;

	while(arr.length > endIdx) {
		let res = await b(startIdx, endIdx);
		//let res = b();
		console.log(res);
		startIdx = endIdx;
		endIdx = endIdx + batchSize;
	}
}

</script>
<button onclick="a()">click</button>
</html>

运行结果
image

相关知识:
Rxjs forkJoin方法:

forkJoin([
      this.aService.getData(),
      this.bService.getData()
    ]).subscribe(resArr => {
      // 此时的返回结果将被按顺序放在一个数组中
      aData = resArr[0];
      bData = resArr[1];
  }

Promise.all()方法

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});
// Expected output: Array [3, 42, "foo"]