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);
            });
        })
5
  • 2
    your code formatting makes my brain bleed when I try to read it Commented Nov 28, 2016 at 5:46
  • 1
    I think you are using callback in both if/else condition. Commented Nov 28, 2016 at 5:58
  • What do you mean by var url = url;? Commented Nov 28, 2016 at 6:01
  • url is the url where request is go am just temporary write url Commented Nov 28, 2016 at 6:15
  • Please run your code through JS lint and fix missing semicolons at ends of lines. I noticed at least two. Commented Nov 28, 2016 at 6:41

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.