您可以使用具有并发选项的Bluebird.map()
来控制同时进行的请求数:
const Promise = require('bluebird');
const http = Promise.promisifyAll(require('http');
var ids = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 6: 56, 7: 7, 8: 8, 5:6 }; // this is random
Promise.map(Object.keys(ids).map(function(dp){
return http.post({url: addr, form: { data: dp }).then(function(body) {
return body.xx;
});
}), {concurrency: 2}).then(function(results) {
// process results here
});
仅供参考,我不明白你想用你的第二个做什么,http.post()
因为你引用的data.x
时间data
是一个数组。我认为代码有点伪代码太多,无法说明您真正想用第二个http.post()
.
否则,您可以编写自己的并发控制代码,首先启动 N 个请求,然后每次完成一个请求,然后启动另一个,直到您无事可做。这是手动编码并发控制的示例:
一次触发 1,000,000 个请求 100 个
或者,您可以像这样自己编写:
const http = require('http');
function httpPost(options) {
return new Promise(function(resolve, reject) {
http.post(options, function(err, res, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
});
});
}
// takes an array of items and a function that returns a promise
function mapConcurrent(items, maxConcurrent, fn) {
let index = 0;
let inFlightCntr = 0;
let doneCntr = 0;
let results = new Array(items.length);
let stop = false;
return new Promise(function(resolve, reject) {
function runNext() {
let i = index;
++inFlightCntr;
fn(items[index], index++).then(function(val) {
++doneCntr;
--inFlightCntr;
results[i] = val;
run();
}, function(err) {
// set flag so we don't launch any more requests
stop = true;
reject(err);
});
}
function run() {
// launch as many as we're allowed to
while (!stop && inflightCntr < maxConcurrent && index < items.length) {
runNext();
}
// if all are done, then resolve parent promise with results
if (doneCntr === items.length) {
resolve(results);
}
}
run();
});
}
var ids = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 6: 56, 7: 7, 8: 8, 5:6 }; // this is random
mapConcurrent(Object.keys(ids), 2, function(item, index) {
return httpPost({url: addr, form: {data: item}}).then(function(body) {
return body.xxx;
});
}).then(function(results) {
// array of results here
}, function(err) {
// error here
});