在 redux 操作中控制异步批处理请求

Controlling Async Batch request inside redux action

我有一个用于在应用程序中进行搜索的 redux 操作。当用户开始搜索时,它会批处理查询并为每个请求发送 30 个查询,并将前 10 个请求排队。每当任何一个请求成功时,它都会将下一个请求添加到请求队列中。所有这一切都是作为一个 redux 动作发生的,只要请求成功,它就会分派动作将结果附加到商店中。如果用户单击 "cancel search" 并输入新的搜索词,我想输入有关如何处理此问题的信息。如何取消现有请求和 redux 操作,使之前的搜索请求不会成功并添加到结果存储?

下面的示例代码:-

function search(queries){
  // split the queries into chunks of size 30
  batches = _.chunks(queries, 30);

  let count = 0;

  //get the first batch manually
  getBatch(batches[0]);

  function getBatch(batch){
    axios.post('url', batch.join(',')).then((response) => {

      // recursively call get batch to get rest of the data
      if(count < batches.length) { getBatch(batches[count++]); }

      // dispatch action to append the result into the store
      dispatch({ type: 'APPEND_RESULT', payload: response })
    }
  }
}

this is a minimal code for sharing the concept

我读过关于 axios 支持的可取消承诺。但是我不确定如何在第二次执行同一函数时控制这个递归调用。

eg: user input will be { ids :[1,2,3,..1000] } I am trying to create batches and sent parallel requests { ids:[1,2, .. 29,30 }, { ids: [31, 32, .. 59,60]} etc.

答案完全恕我直言

在我看来,整个解决问题的方法都在这里被打破了。您将通过不断询问任何输入更改来关闭您的服务器。想象一下您的网站将消耗多少移动流量!

此处最好的解决方法是:

  1. _.debounce 添加到您的输入中,等待时间较短(100 毫秒较好)
  2. 内存中只有一个查询。对于来自 user 的每个新事件,输入 cancel 请求并覆盖当前请求。
  3. 用每个服务器响应的数据调度一个动作

这看起来像是 redux observable 的候选人。您可以创建一个可观察对象,然后添加一个去抖动(如上面一条评论中提到的),并且您可以在当前请求完成时轻松取消或切换映射到新请求,这样就不会考虑前一个队列中的任何剩余项目。