我怎样才能节制堆栈的API请求?

我有一个id数组,我想为每个id做一个api请求,但是我想控制每秒有多less个请求,或者更好的是,在任何时候只有5个打开的连接,并且当一个连接是完成,取下一个。

目前我有这个,它只是在同一时间发射所有的请求:

_.each([1,2,3,4,5,6,7,8,9,10], function(issueId) { github.fetchIssue(repo.namespace, repo.id, issueId, filters) .then(function(response) { console.log('Writing: ' + issueId); writeIssueToDisk(fetchIssueCallback(response)); }); }); 

就个人而言,我会使用Bluebird的.map()concurrency选项,因为我已经使用Promise和Bluebird来处理任何asynchronous。 但是,如果您想查看一下手动编码的计数器scheme,它可以限制同时运行多less个并发请求,如下所示:

 function limitEach(collection, max, fn, done) { var cntr = 0, index = 0, errFlag = false; function runMore() { while (!errFlag && cntr < max && index < collection.length) { ++cntr; fn(collection[index++], function(err, data) { --cntr; if (errFlag) return; if (err) { errFlag = true; done(err); } else { runMore(); } }); } if (!errFlag && cntr === 0 && index === collection.length) { done(); } } runMore(); } 

与蓝鸟:

 function fetch(id) { console.log("Fetching " + id); return Promise.delay(2000, id) .then(function(id) { console.log(" Fetched " + id); }); } var ids = [1,2,3,4,5,6,7,8,9,10]; Promise.map(ids, fetch, { concurrency: 3 }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.1/bluebird.min.js"></script> <!-- results pane console output; see http://meta.stackexchange.com/a/242491 --> <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> 

将您的数据分割成您想要的并发连接数量。 使用setTimeout进行计划,并使用完成callback来处理子数组的其余部分。

将setTimeout包装在自己的函数中,以便在delayed_fetch()调用时将variables值冻结为它们的值。

 function delayed_fetch(delay, namespace, id, issueIds, filters) { setTimeout( function() { var issueId=issueIds.shift(); github.fetchIssue(namespace, id, issueId, filters).then(function(response) { console.log('Writing: ' + issueId); writeIssueToDisk(fetchIssueCallback(response)); delayed_fetch(0, namespace, id, issueIds, filters); }); }, delay); } var i=0; _.each([ [1,2] , [3,4], [5,6], [7,8], [9,10] ], function(issueIds) { var delay=++i*200; // millisecond delayed_fetch(delay, repo.namespace, repo.id, issueIds, filters); }); 

我build议使用喉咙只是为了: https : //github.com/ForbesLindesay/throat