0

I was using nested for loops but though I am not getting required result, I moved to closures

Here is the skeleton of my previous code

// First for loop
for(data)
{
    connection.query(records as per data)
    if(!error)
    {   
        // Second for loop
        for(abc)
        {
            if(condition)
            {
                condition1.....
                    result=call method1
                condition2.......
                    result=call method2
                conditionN....
            }
            else
            {
            }

            //After completion second for loop push result into array
            resultArray.push(result)

            // After completion on both for loop callback array         
            if(EOD first for && EOD second for)
            {
                callback(resultArray)
            }
        }
    }
}

And here the code where I am getting error while using closure

function secondFunction(data)
{
    console.log("secondFunction"+data)

    var result = [];
    for (var i = 0; i < data.length; i++) {

        result.push( function() {
            console.log(data[i].type)
        } );
    }
    return result;
}

function firstFunction() 
{
    for (var j = 0; j < r.abc.length; j++) {

         connection.query(" my sql query on r.abc[j].etc ", function(err, rows){

            if (!err)
            {   
               console.log("length"+rows.length)

               var fnlist = secondFunction(rows);
               fnlist[j]();

               console.log("first for")    
            }
            else
            {
                console.log('Error in performing query')
            }
        });
    }
}

firstFunction()

Output-

length11
secondFunction[object Object],[object Object]
TypeError: fnlist[j] is not a function

I have followed example5 of this

Specifically, Is this right way to use closures in nodejs? Can we use it in connection.query() ? If yes then how else how can we achieve this?

Community
  • 1
  • 1
Priyanka Pawar
  • 205
  • 1
  • 4
  • 16

1 Answers1

-1

you are accessing a invalid position of the array in your "for" instruction ... try :

for (var i = 0; i < data.length -1; i++) {

=]