首页 > 解决方案 > 等待 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)

} 

标签: javascriptreactjsrestdelaytimedelay

解决方案


最简单的方法是创建一个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();
}

推荐阅读