简体   繁体   中英

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

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...
        });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM