如何使用瓶颈npm模块

时间:2017-05-01 06:13:29

标签: javascript node.js npm module

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

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

基本nodejs和express中的瓶颈示例可以提供很多帮助。

这是npm包:bottleneck npm module

1 个答案:

答案 0 :(得分:1)

我建议先了解承诺,然后查看请求承诺。以下是如何使用承诺从简单的气象服务获取信息:

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...
        });
});
相关问题