如何使用瓶颈 npm 模块

Nir*_*hal 8 javascript module node.js npm

我刚刚发现了这个瓶颈 npm 模块来限制每秒的请求数。我理解bottleneck() 构造函数,但无法理解submit 和schedule() 方法,可能是因为我是node 的初学者并且不了解promise。

无论如何,我找不到任何关于使用谷歌瓶颈的例子。

基本 nodejs 和 express 中的瓶颈示例可能会有很大帮助。

这是 npm 包:bottleneck npm module

小智 7

我建议先了解 Promise,然后研究 request-promise。以下是如何将其与 promise 一起使用以从简单的天气服务中获取信息:

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...
        });
});
Run Code Online (Sandbox Code Playgroud)