1

I am creating project using javascript and nodejs. I am integrating callback in my function inside for loop with condition basis,but am unable to do this.my problem is callback is completed on first iteration of loop. here is my code:

function tagEndpointNames(callback) {

    var data = userGenerateToken();
    var sql = "SELECT * FROM topology_data WHERE topology_coordinates !='' and topology_uuid is not null"

    var query = conn.query(sql, function(err, tagEndpointNames) {

        for (var i = 0; i < tagEndpointNames.length; i++) {
            var topologytagData = {
                "topology_tag": tagEndpointNames[i].topology_uuid
            }

            var tpCooridinates = JSON.parse(tagEndpointNames[i].topology_coordinates);

            for (var j = 0; j < tpCooridinates.stageObjects.length; j++) {

                if (tpCooridinates.stageObjects.length) {

                    if (tpCooridinates.stageObjects[j].endPointId) {

                        if (isGuid(tpCooridinates.stageObjects[j].endPointId)) {

                            var endPointUUID = tpCooridinates.stageObjects[j].endPointId;
                            var _ro = require('request');

                            var url = url;

                            var _d = '';

                            _ro({
                                url: url,
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'Authorization': 'Bearer ' + data['access_token']
                                },

                                json: topologytagData

                            }, function(_e, _r, _b) {

                                if (_r.statusCode == 200 && !_e) {

                                    callback()
                                        //return;
                                } else {

                                    callback()
                                    console.log("andarss")
                                    return;
                                }

                            })
                        }
                    }
                }
            }
        }

    })
}

Here is the function call:

tagEndpointNames(function(){
            console.log ('Server Closed during MIGRATION JOB 4');
            server.close(function () {
                process.exit(0);
            });
        })
Giovanni Lobitos
  • 852
  • 7
  • 19
Karan
  • 1,048
  • 2
  • 20
  • 38

3 Answers3

0

When you are running asynchronous process with callback in a for loop, remember that the callback from callee will be fired in the first event completed inside the loop. In your case request lib call is an asynchronous process inside for loop, you need to handle all callback from all the request call before you want to callback the callee.

Please read: How to write asynchronous functions for Node.js

Community
  • 1
  • 1
iKoala
  • 870
  • 4
  • 11
0

Maybe it's time for you to start using Javascript Promise.

Giovanni Lobitos
  • 852
  • 7
  • 19
0

The async library for Node will help you for doing this kind of tasks.

Use async waterfall.It Runs an array of functions in series, each passing their results to the next in the array. However, if any of the functions pass an error to the callback, the next function is not executed and the main callback is immediately called with the error.

js

var create = function (req, res) {
    async.waterfall([
        _function1(req),
        _function2,
        _function3
    ], function (error, success) {
        if (error) { alert('Something is wrong!'); }
        return alert('Done!');
    });
};

function _function1 (req) {
    return function (callback) {
        var something = req.body;
        callback (null, something);
   }
}

function _function2 (something, callback) {
    return function (callback) {
       var somethingelse = function () { // do something here };
       callback (err, somethingelse);
    }
}

function _function3 (something, callback) {
    return function (callback) {
      var somethingmore = function () { // do something here };
      callback (err, somethingmore);
    }
}

Reference

Community
  • 1
  • 1
Muhsin Keloth
  • 7,855
  • 7
  • 39
  • 59