有多种方法。
顺序请求
您可以使用 RxJS range 运算符和映射运算符 concatMap 来顺序调用每个请求。
import { range } from 'rxjs';
import { concatMap } from 'rxjs';
range(1, N).pipe( // <-- will emit 1-N numbers
concatMap(id => myAPI.delete(id)) // <-- set the correct `id` for each request here
).subscribe(
res => console.log(res),
err => console.log(err),
);
由于我们使用concatMap 运算符,每个id 的请求将在前一个请求完成之前等待。
您还可以针对不同的行为使用其他映射运算符,例如 switchMap、flatMap 和 exhaustMap。差异 b/n 他们here。
其他方法 - 并行请求
完成并行请求
您可以使用 RxJS 的 toArray 和 forkJoin() 运算符进行多个并发调用。它同时订阅多个可观察对象。
import { range, forkJoin } from 'rxjs';
import { concatMap, toArray } from 'rxjs/operators';
range(1, N).pipe( // <-- will emit 1-N numbers
concatMap(id => myAPI.delete(id)), // <-- set the correct `id` for each request here
toArray(), // <-- buffer all notifications and emit once as an array
concatMap(reqs => forkJoin(reqs))
).subscribe(
res => console.log(res),
err => console.log(err),
);
缓冲的并行请求
大多数浏览器对单个域的最大并行请求数有硬性限制(例如 Chrome - 6)。如果你遇到这个问题,你可以使用 RxJS 的 bufferCount 操作符而不是 toArray 操作符来控制最大并行请求数。
import { from, forkJoin } from 'rxjs';
import { concatMap, bufferCount } from 'rxjs';
range(1, N).pipe( // <-- will emit 1-N numbers
concatMap(id => myAPI.delete(id)), // <-- set the correct `id` for each request here
bufferCount(6), // <-- adjust number of parallel requests here
concatMap(reqs => forkJoin(reqs))
).subscribe(
res => console.log(res),
err => console.log(err),
);