簡體   English   中英

節氣門/去抖每秒的呼叫數

[英]Throttle / Debounce number of calls per second

我正在使用一個API,該API僅允許您使用承諾請求庫(例如request-promiseaxios )每秒進行200次調用(1000毫秒),如何使用rx來反跳/限制對URL /服務器的請求。 JS? 我在rx文檔中注意到了節流方法 ,但它不會每秒計算調用次數。

這個函數包裝了一個promise,並將它們排隊以解決API速率限制。 我正在尋找與Rx類似的功能。

var Promise = require("bluebird")

// http://stackoverflow.com/questions/28459812/way-to-provide-this-to-the-global-scope#28459875
// http://stackoverflow.com/questions/27561158/timed-promise-queue-throttle

module.exports = promiseDebounce

function promiseDebounce(fn, delay, count) {
  var working = 0, queue = [];
  function work() {
    if ((queue.length === 0) || (working === count)) return;
    working++;
    Promise.delay(delay).tap(function () { working--; }).then(work);
    var next = queue.shift();
    next[2](fn.apply(next[0], next[1]));
  }
  return function debounced() {
    var args = arguments;
    return new Promise(function(resolve){
      queue.push([this, args, resolve]);
      if (working < count) work();
    }.bind(this));
  }
}

因此,前幾天我遇到了類似的問題,即限制對資源的訪問速率。 我遇到了這個倉庫bahmutov / node-rx-cycle 這是我整理來演示的Plunker演示中的示例。 它從文本輸入字段獲取輸入並將其添加到<ul> 每個<li>僅每1000毫秒添加一個,其他的則排隊。

// Impure
const textInput = document.querySelector('.example-input');
const prependToOutput = function(item) {
  const ul = document.querySelector('.example-output');
  const li = document.createElement('li');
  li.appendChild(document.createTextNode(item));
  ul.insertBefore(li, ul.firstChild);
};

// Pure
const eventTargetValue = function(ele) { return ele.target.value; };
const textInputKeyUpStream = Rx.Observable
  .fromEvent(textInput, 'keyup')
  .map(eventTargetValue);

// Stream
rateLimit(textInputKeyUpStream, 1000)
  .timeInterval()
  .map(function(ti) { return ti.value + ' (' + ti.interval + 'ms)'; })
  .subscribe(prependToOutput);

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM