0

looking for a way to make a node function synchronized within a loop ex:

var abc = (count) => {
    for (var i = 0; i < count; i++) {
        var data = { "userName": "admin@xyz.com", "password": "xyz123#" };
        sendPost(data, function (err, data) {
            if (err) {
                console.log(err);
            }
            else {
                console.log(data);
            }
            console.log("sequence " + i);
        });

    }
    console.log("end of function");
}

var sendPost = function (data, callback) {

    console.log("post request :: " + JSON.stringify(data));
    var formData = JSON.stringify(data);
    var contentLength = formData.length;


    request({
        headers: {
            'Content-Type': 'application/json'
        },
        uri: "https://someurl/Login",
        body: formData,
        method: 'POST'
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            callback(null, body);
        } else {
            console.log(error);
            callback(error);
        }
    })
}
abc(3);

required response sequence should be post request :: obj -->>response -->>count -->>end of function

actual response is all async and the count is always 3

does node has some way to make function all sync

rahul
  • 880
  • 3
  • 14
  • 25

0 Answers0