响应回来发送下一个请求
2022/4/9 小于 1 分钟
一个页面需要发送大量的请求,但是后端的服务没有做并发处理或前端浏览器有并发请求限制(大约6-8个),这个时候最好的办法就是限制请求的发送个数,或者在响应回来之后在发送下一个请求。
场景:第一个请求响应回来之后发送下一个请求;
const http = require('./http.js');
// 需要发送大量请求的数据,例:每一条数据为一个新增操作
const resource = [
{ a: 1, b: 2 },
{ a: 2, b: 3 },
{ a: 3, b: 4 }
];
let promise = Promise.resolve();
resource.forEach((item, index) => {
const _item = item;
let _then = () => {
// 在_then方法中执行一下次的请求,并返回一个promise
return recursion(_item);
}
// 上一个响应回来之后调用_then方法;
promise = promise.then(_then);
})
function recursion(item) {
return http("xx/xx", 'post', item).then(res => {
return res;
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25