繁体   English   中英

Lodash节气门或循环内反跳的问题

[英]Issue with Lodash Throttle or Debounce within the loop

我正在调用一个提取请求,试图通过使用Lodash Throttle或Debounce来限制该请求。 我正在遍历一些数组并立即调用函数,这会影响服务器以502进行响应。我试图通过Throttle减慢请求的速度。 下面的代码应解释我的结构。 这个例子不起作用,我也不知道为什么吗?


    function doSomething(i) {
      console.log('Doing something: ' + i)
    }


    for (var i = 0; i < 50; i++) {

       _.throttle( function() { doSomething(i) }, 15000);

    }

应该每15秒调用一次函数doSomething(),并且应该堆叠对该函数的其他请求。

_.throttle()不能以这种方式使用。 正确的方法是先存储结果。

var throttledDoStomething = _.throttle(doSomething, 15000)

for (var i=0; i < 50; i++) {
  throttledDoSomething(i)
}

回复评论:

在这种情况下,节气门可能不是正确的选择。 您可能想通过Promise使用异步功能。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

function asyncDoSomething(i) {
  return new Promise((resolve, reject) => {
    console.log('Doing something: ' + i);
    setTimeout(()=>{
      resolve(i);
    }, 15000)
  })
}

async function doSomethingLoop() {
  for (var i = 0; i < 50; i++) {
    await asyncDoSomething(i);
  }
}

doSomethingLoop();

文件建议您首先要进行节流功能。
放置参数需要使用匿名函数(在我的情况下,我使用了数组函数)。

function doSomething(i) {
  console.log("Doing something: " + i);
}

const throttledSomething = _.throttle(() => { doSomething(i)}, 5000);

for (var i = 0; i < 50; i++) {
  throttledSomething(i);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM