簡體   English   中英

使用RxJS進行速率限制

[英]Rate Limiting with RxJS

目前,我發現了RxJS,而我的第一個嘗試就是試圖對API請求進行速率限制。

我不知何故丟失了一些東西,只是“未定義”。

我究竟做錯了什么?

const Rx = require('rx');
const request = require('request');

function f() {
  return Rx.Observable.from(arguments);
}

function expand(condensedId) {
  console.log('requesting', condensedId)
  return f(request(INDEX_URL + '/' + condensedId));
}

const INDEX_URL = 'http://jsonplaceholder.typicode.com/posts';

var source = f([1,2,3,4,5,6,7])
  .windowWithTimeOrCount(5000, 2)//rate limitation, 2 every 5 seconds
  .flatMap(condensed => expand(condensed))
  .map(entry => entry.title);

var subscription = source.subscribe(
  function (x) {
    console.log('title: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });

Rx.Observable.from期望可迭代,並且我認為對request()的響應不是可迭代的。 您可以傳遞一個函數,將一個Promise或Observable返回給flatMap ,它將返回一個流,該流將發出已解析的數據。

因此,讓我們使用request-promise代替request並在我們的expand函數中返回Promise。 另外,讓我們使用cheerio庫提取html標題:

const Rx = require('rx');
const request = require('request-promise');

// HTML parsing library
const cheerio = require('cheerio');

function f() {
  return Rx.Observable.from(arguments);
}

const INDEX_URL = 'http://jsonplaceholder.typicode.com/posts';

// Return an Observable of resolved responses
function expand(condensedId$) {
  return condensedId$.flatMap(id => request(INDEX_URL + '/' + id));
}

var source = f([1,2,3,4,5,6,7])
  .windowWithTimeOrCount(5000, 2)//rate limitation, 2 every 5 seconds
  .flatMap(condensed => expand(condensed))
  .map(body => {
    const $ = cheerio.load(body);
    return $('title').text();
   });

暫無
暫無

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

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