Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

rxjs - How to make parallel api call in angular in loop which run for 10 times

I have a array of length 10 var a = [1, 2, 3, ....10]; // length=10;

how do I make 2 parallel Api call for same array length;

forkJoin([
  a.map(response => {
   return this.http.post('/api/1', response);
 }),
  a.map(response => {
  return this.http.post('/api/2', response)
  })
]
).subscribe(result => ) // i am getting [Observable, Observable] here
question from:https://stackoverflow.com/questions/65829735/how-to-make-parallel-api-call-in-angular-in-loop-which-run-for-10-times

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use JS Array#flatMap to create an array containing both requests for each element in the array and altogether flatten them. That should result in 20 parallel requests with 2 requests for each element in the array.

forkJoin(
  arr.flatMap(item => [
    this.http.post(`/api1/{item}`, response),
    this.http.post(`/api2/{item}`, response)
  ])
).subscribe({
  next: res => {
    // `res` is an array with 20 elements each corresponding to it's respective response
  },
  error: error => {
    // handle error
  }
});

If you think flatMap (ES2019) might not be available is some browsers yet, you could use Array#map with the solution shown here to flatten the array.

forkJoin(
  [].concat.apply([],  // credit: https://stackoverflow.com/a/10865042/6513921
    arr.map(item => [
      this.http.post(`/api1/{item}`, response),
      this.http.post(`/api2/{item}`, response)
    ])
  )
).subscribe();

Update: include condition !order.price

You'd need to filter the undefined elements in the array introduced by the condition !order.price with Array#map.

forkJoin(
  [].concat.apply([],  // credit: https://stackoverflow.com/a/10865042/6513921
    arr.map(order => 
      !order.price 
        ? [
            this.http.post(`/api1/{item}`, response),
            this.http.post(`/api2/{item}`, response)
          ]
        : null
    )
  )
  .filter(item => !!item)  // <-- remove undefined/null elements
).subscribe();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...