-1

Am using a function to save data. Using the http.request option. It is working fine. If I call the same function in a loop, some of the data not saving in database. Also getting the parse error message for some response.

How Can I call the function of http.request in a loop?

for (var i = 1; i <= 23; i++) {
    turn_timer(i);
}

function turn_timer(nos) {
    try {
        var str = "num=" + nos;
        var len = str.length;

        win_settings.headers = {
            'Content-length': len,
            'Content-Type': 'application/x-www-form-urlencoded'
        }

        var request = http.request(win_settings, function(response) {
            response.on('data', function(data) {

            });

            response.on('error', function(err) {

            });

            response.on('end', function() {

            });
        });

        request.on('error', function(err) {

        });

        request.write(str + "\0");
        request.end();

    } catch (err) {
        console.log(err);
    }
}
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
swaraj
  • 29
  • 1
  • 7

2 Answers2

0

Check the scope of your variable that stores message because async function call may overwrite it.

Dongho Yoo
  • 1,506
  • 16
  • 16
0

I believe your problem is because you are using a for loop, instead of going with a more asynchronous approach. Here is a quick attempt to solve your problem. I have omitted some of your code, as it seemed to be incomplete. I have left the important parts and added a few things based on an answer to a similar question.

var http = require('http'),
    async = require('async');

function turn_timer(n, callback) {
    var var str = "num=" + n,
        len = str.length,
        req;

    win_settings.headers = {
        'Content-length': len,
        'Content-Type': 'application/x-www-form-urlencoded'
    };

    req = http.request(options, function(response) {
        ...
        callback(null);
    });

    req.on('error', function(err) {
        ...
        callback(err);
    });

    req.end();
}

async.timesSeries(23, function (n, next) {
    turn_timer(options, function(err) {
        next(err);
    });
});

For more information, you can read more about async.timesSeries here: https://github.com/caolan/async#timesseriesn-callback

Community
  • 1
  • 1
Brian Lewis
  • 5,739
  • 1
  • 21
  • 28