Ben*_*Ben 4 asynchronous function code-duplication node.js
我需要发出几个API请求,然后对组合结果集进行一些处理.在下面的示例中,您可以通过复制相同的请求代码来查看3个请求(到/创建),但我希望能够指定要生成的请求数.例如,我可能希望运行相同的API调用50次.
如何在不重复API调用函数的情况下进行n次调用?
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, res) {
if (err) {
callback(err, null);
}
callback(null, res.body.id);
});
},
function(callback){
request.post('http://localhost:3000/api/store/create')
.send(conf)
.end(function (err, res) {
if (err) {
callback(err, null);
}
callback(null, res.body.id);
});
}
],
function(err, results){
if (err) {
console.log(err);
}
// do stuff with results
});
Run Code Online (Sandbox Code Playgroud)
首先,在函数中包装要多次调用的代码:
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);
});
}
Run Code Online (Sandbox Code Playgroud)
然后,使用async.times函数:
async.times(50, function (n, next) {
doRequest(function (err, result) {
next(err, result);
});
}, function (error, results) {
// do something with your results
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4817 次 |
| 最近记录: |