我需要发出几个API请求,然后对组合结果集进行一些处理.在下面的示例中,您可以通过复制相同的请求代码来查看3个请求(到/创建),但我希望能够指定要生成的请求数.例如,我可能希望运行相同的API调用50次.
async.parallel([ function(callback){ request.post('http://localhost:3000/create') .send(conf) .end(function (err,res) { if (err) { callback(err,null); } callback(null,res.body.id); }); },function(callback){ request.post('http://localhost:3000/create') .send(conf) .end(function (err,function(callback){ request.post('http://localhost:3000/api/store/create') .send(conf) .end(function (err,res.body.id); }); } ],function(err,results){ if (err) { console.log(err); } // do stuff with results });
解决方法
首先,在函数中包装要多次调用的代码:
var doRequest = function (callback) { request.post('http://localhost:3000/create') .send(conf) .end(function (err,res) { if (err) { callback(err); } callback(null,res.body.id); }); }
然后,使用async.times功能:
async.times(50,function (n,next) { doRequest(function (err,result) { next(err,result); }); },function (error,results) { // do something with your results }