[英]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.