javascript - 等待 X 时间,然后继续循环 - JS React
问题描述
我有一个循环循环并创建 REST 查询,每次都创建和运行不同的查询。
在未来,我想象可以进行的 REST 查询的数量将远远超过浏览器一次处理的数量(超过 20,000 个)。
我想做一些事情,计算已经完成了多少次循环,每 500 次左右,暂停几秒钟,让浏览器赶上 REST 响应,然后继续。
这是如何在 React JS 中完成的?
示例代码:
for (var i = 0; i < array.length; i++)
{
query += i;
axious.get(query) . then { ...does stuff here... }
//want something along the lines of if multiple of 500, wait(1000)
}
解决方案
最简单的方法是创建一个waitIf
返回 aPromise
并接受条件的函数。如果条件为true
,则等待然后执行回调,否则,将直接执行回调。
一个简单的实现将是。
function waitIf(condition, duration, callback) {
if (condition) {
// return a Promise that wait for a `duration` ms using timeout
return Promise((resolve) => {
setTimeout(() => {
resolve(callback());
}, duration);
})
}
return callback();
}
for (let i = 0; i < array.length; i++) {
query += i;
// unify the call here
waitIf(i % 500 === 0, 1000, () => axious.get(query)).then();
}
推荐阅读
- python - 在 for/while 循环中,在满足条件后,它会读取以下任何条件吗?
- sql - MS Access using VBA and Form, build a query string and run it
- google-cloud-build - 从失败的构建中存储工件
- r - df % > % mutate(price_scal = scale(price), hd_scal = scale(hd) 中的错误:找不到函数“% > %”
- r - 基于另一列中的变量填充 R [使用 if 语句?] 中的一列
- javascript - 数组包含未在二维数组中获取结果
- arrays - 违反 Fortran 形状匹配规则
- html - 使用 VBA 在线订购
- pandoc - Exams2pandoc 错误消息 - 无效的模板
- freeradius - 自由半径会计过滤器