在我的应用程序的反应,我有一个网格。用户可以一次选择多个网格行,然后单击一个按钮对所选网格行执行批量操作。作出反应 - 控制多个Ajax调用
在服务器端我有一个脚本,我想为每个选定的行执行(使问题变得简单,我在下面的示例中针对每个选定行调用“jsonplaceholder.typicode.com”)的批量操作按钮。点击批量操作按钮后,我会在操作创建器中获取selectedRows,在迭代选定行的同时为每个选定行创建ajax调用。
由于selectedRows可能包含超过1000个项目,如果我只是反复让使用foreach循环Ajax调用,浏览器页面最终可能会停止响应每个请求都解决了。因此,我使用下面的解决方案,以5批为单位发送请求,然后等到这5个问题解决。上述
// Action creator, selectedRows is an array.
function onGridRowsSelection(selectedRows) {
makeBatchCalls(selectedRows,5)
}
async function makeBatchCalls(selectedRows, length) {
let test = arrayIds.reduce((rows, key, index) => (index % length == 0
? rows.push([key])
: rows[rows.length-1].push(key)) && rows, []);
let Batchresults = []; //convert them to two dimensionl arrays of given length [[1,2,3,4,5], [6,7,8,9,10]]
for (calls of test) {
Batchresults.push(await Promise.all(calls.map((call)=>{
fetch(`https://jsonplaceholder.typicode.com/posts/${call}`)
})
));
}
return Promise.all(Batchresults); //wait for all batch calls to finish
}
解决方案工作正常,但有一个问题,
- 从网格中选择超过5行,然后点击批量操作按钮,
- 再次选择超过5行,并点击批量操作按钮,
- 现在我看到同时启动10个请求。
我怎么能限制呢?
跟进质询,这里提到的被要求在React - controlling async calls smartly without any side effect in complex applications
这个问题的JavaScript, React - sending multiple simultaneous ajax calls
感谢您的回答,让我试试这个。 –