不确定您所说的后端仅允许大约 70 个请求。但是如果你想控制一次并行请求的数量,你可以使用 RxJS 的 from、bufferCount 和 forkJoin 函数和 concatMap 运算符。
-
尽量避免toPromise()。切换回熟悉的 Promise 范式是一种更简单的方法,但它在 RxJS 7 中为 deprecated,将在 RxJS 8 中消失。而是尝试订阅 observables。
-
对于受控的并行请求,请尝试以下操作
const reqs = this.data.map(item => this.http.post(url, item, { headers: (reqHeader) }))
from(reqs).pipe(
bufferCount(6), // <-- adjust number of parallel requests here
concatMap(buffer => forkJoin(buffer))
).subscribe(
res => console.warn(res),
err => console.log(err),
() => console.log('complete')
);
更新:延迟每个请求
您可以放弃bufferCount,而是单独切换到每个请求并使用显式延迟。试试下面的
from(this.data).pipe(
concatMap(item => this.http.post(url, item, { headers: (reqHeader) }).pipe(
delay(3000) // <-- wait 3 seconds b/n each request
))
).subscribe(
res => { },
err => { }
);
更新:计算排放量
您可以引入一个变量(例如count)并使用map 运算符来返回计数和响应。
试试下面的
someFunc() {
let count = 0;
from(this.data).pipe(
concatMap(item => this.http.post(url, item, { headers: (reqHeader) }).pipe(
map(res => {
count++;
return {
count: count,
response: res
}
}),
delay(3000) // <-- wait 3 seconds b/n each request
))
).subscribe(
res => {
console.log(res.count); // <-- the count of the emission
console.log(res.response); // <-- the response from `this.http.post()`
},
err => { }
);
}