简体   繁体   English

使用RxJS进行速率限制

[英]Rate Limiting with RxJS

I'm discovering RxJS at the moment and one of my first tries was trying to achieve a rate limiting on API requests. 目前,我发现了RxJS,而我的第一个尝试就是试图对API请求进行速率限制。

Somehow I am missing something and getting in the output just "undefined". 我不知何故丢失了一些东西,只是“未定义”。

What am i doing wrong? 我究竟做错了什么?

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 expects an iterable, and I don't think the response to request() is an iterable. Rx.Observable.from期望可迭代,并且我认为对request()的响应不是可迭代的。 You can pass a function that returns a Promise or an Observable to flatMap , and it will return a stream that will emit the data that's resolved. 您可以传递一个函数,将一个Promise或Observable返回给flatMap ,它将返回一个流,该流将发出已解析的数据。

Because of this, let's use request-promise instead of request and return a Promise in our expand function. 因此,让我们使用request-promise代替request并在我们的expand函数中返回Promise。 Additionally, let's use the cheerio library to extract the html title: 另外,让我们使用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