微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐