【问题标题】:Send Series of Batched API Requests发送一系列批处理 API 请求
【发布时间】:2022-06-11 20:16:21
【问题描述】:

寻找一种高效的方法来批量发送大约 1000 多个请求,例如并行发送 6 个请求,当这 6 个请求完成后,发送下一个 6

批量发送将阻止浏览器请求队列完全阻塞在批处理调用过程中可能发生的任何其他 API 请求

我之前使用 RxJS 完成了此操作(下面的示例),但想知道是否有基于 fetch Promise 的等效方法?

// Array of observables
const urls = [
  this.http.get('url1'),
  this.http.get('url2'),
  this.http.get('url3'),
  ...
];


bufferedRequests(urls) {
  from(urls).pipe(
    bufferCount(6),
    concatMap(buffer => forkJoin(buffer))
  ).subscribe(
    res => console.log(res),
    err => console.log(err),
    () => console.log('complete')
  );
}

【问题讨论】:

    标签: javascript reactjs promise rxjs


    【解决方案1】:

    我之前用过bottleneck

    它允许您使用客户端速率限制器限制您的请求。您可以选择每分钟发送多少个请求以及可以运行多少个并发请求。

    您可以设置limiter

    const limiter = new Bottleneck({
     maxConcurrent: 1,
     minTime: 333 //this will execute 3 requests every second, aka wait 333 ms to execute the next request
    });
    

    然后用它包装你的函数。

    const wrapped = limiter.wrap(myFunction);
    
    wrapped(arg1, arg2)
    .then((result) => {
      /* handle result */
    });
    

    在您的情况下,我会编写一个函数来包装获取请求并返回一个承诺。然后,我会用限制器包装它。这是一个例子:

    const throttledGetMyData = limiter.wrap(yourFetchFunction);
    
      const allThePromises = requests.map(item => {
        return throttledGetMyData(request);
      })
      try {
        const results = await Promise.all(allThePromises);
        console.log(results);
      } catch (err) {
        console.log(err);
      }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多