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,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
}

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...