简体   繁体   English

如何批量请求api?

[英]How to request api in batch?

I have lots of items to post to server. 我有很多项目要发布到服务器。 I've done this in one call since server accepts any number of items but it actually doesn't suit my situation well as I have timeout on clientside and number of items can grow without any limit. 我已经在一次通话中完成了这个,因为服务器接受任意数量的项目,但它实际上不适合我的情况,因为我在客户端有超时,项目数量可以增长没有任何限制。 so it might be saved on server, I don't get the response back and next time I call the api, number of items accumulate.. 所以它可能保存在服务器上,我没有得到回复,下次我打电话给api,积累了多少项目..

So I'd like to handle this as a batch. 所以我想把它作为批处理。

Client sends 10 items, wait for the server response. 客户端发送10个项目,等待服务器响应。 Once response is back, process it on client side then send another 10 items to server and so on. 一旦响应回来,在客户端处理它然后再向服务器发送10个项目,依此类推。

How would I be achieve this? 我怎么能实现这个目标? PromiseAll ( or combineLatest?)would fire request in parallel but what I want is sequential as I understand. PromiseAll(或combineLatest?)将并行触发请求但我想要的是顺序,据我所知。

This is my test method and not working as I'd like to return observable when it's all done. 这是我的测试方法而不起作用,因为我想在完成所有操作后返回observable。

private test(data):Observable<any>{

    const saveFormInstanceURL = this._networkService.serverUrl + this.SAVE_FORM_INSTANCE_SUFFIX;

    let i = 0;

    return from([data,data,data,data,data]).pipe(
      concatMap(postBody => {
        i++;
        return this._networkService.post(saveFormInstanceURL,postBody)
      })
    ).subscribe(val => {
      console.log('concatMap:', val);
      if (i === 4){
          console.log('all finished');
          return of([]);
        }
    });
  }

You can do it with RxJs, the code snippet below is for processing one by one however, you can set the interval depending on your needs. 您可以使用RxJs执行此操作,下面的代码片段是逐个处理的,但您可以根据需要设置间隔。

interval(100) 
    .pipe(
      take(this.yourArray.length),
      map(i => this.yourArray[i])
    )
    .subscribe(item => {
      console.log(item); // do your thing
    });

This if for 10 by 10 processing with 1 seconds of interval (100 ms for each): 这个用于10到10的处理,间隔为1秒(每个100毫秒):

interval(100)
.pipe(
  take(this.yourArray.length),
  bufferCount(10)
)
.subscribe(itemArray=> {
  console.log(itemArray);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM