Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call same function many times and process combined result set

I have a requirement to make several API requests and then do some processing on the combines result sets. In the example below, you can see that 3 requests are made (to /create) by duplicating the same request code however I would like to be able to specify how many to make. For example, I may wish to run the same API call 50 times.

How can I make n calls without duplicating the API call function n times?

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
});
like image 784
Ben Avatar asked Jan 08 '23 19:01

Ben


1 Answers

First, wrap the code that you want to call many times in a function:

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);
        });
}

Then, use the async.times function:

async.times(50, function (n, next) {
    doRequest(function (err, result) {
      next(err, result);
    });
}, function (error, results) {
  // do something with your results
}
like image 187
Rodrigo Medeiros Avatar answered Jan 20 '23 17:01

Rodrigo Medeiros