Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the bottleneck npm module

I just found out about this bottleneck npm module to limit the no of requests per second. I understood the bottleneck() constructor, but cannot understand the submit and schedule() methods, probably because I am a beginner in node and don't know about promise.

Anyway, I couldn't find any examples about using bottleneck from google.

A bottleneck example in basic nodejs and express could help a lot.

Here is the npm package: bottleneck npm module

like image 578
NirabhroMakhal Avatar asked May 01 '17 06:05

NirabhroMakhal


People also ask

What is bottleneck in node JS?

Bottleneck is a lightweight and zero-dependency Task Scheduler and Rate Limiter for Node. js and the browser. Bottleneck is an easy solution as it adds very little complexity to your code. It is battle-hardened, reliable and production-ready and used on a large scale in private companies and open source software.

What is bottleneck in Javascript?

A bottleneck is a phenomenon where the performance or capacity of an entire system is limited by a single or limited number of components or resources. In order to improve the performance, we need to remove these.


1 Answers

I'd recommend learning about promises first, and look into request-promise. Here is how you could use it with promises to get info from a simple weather service:

var rp = require("request-promise");
var Bottleneck = require("bottleneck");


// Restrict us to one request per second
var limiter = new Bottleneck(1, 1000);


var locations = ["London","Paris","Rome","New York","Cairo"];

// fire off requests for all locations
Promise.all(locations.map(function (location) {

    // set up our request
    var options = {
        uri: 'https://weatherwebsite.com?location=' + location,
        json: true
    };

    // run the api call. If we weren't using bottleneck, this line would have just been
    // return rp(options)
    //    .then(function (response) {...
    //
    return limiter.schedule(rp,options)
        .then(function (response) {
            console.log('Weather data is', response);
        })
        .catch(function (err) {
            // API call failed...
        });
});
like image 155
Tomh Avatar answered Oct 26 '22 11:10

Tomh