# Recursive function in JS

EDIT:

The code i provide includes a asynchron task in each interation, therefor i need the recursive function, my question is how to beautify the code and apply the proper use.

I want to:

• Remove the processTask(); function call and let it call itself instead.
• Choose the best function declaration.

connection.query(queryString, function (err, rows, fields) {
if (err) return throwSQLError(err, req, res, connection);

var rowLength = rows.length;

// Iterate over all tasks with a recursive function
var processTask = function () {
// I do asynch stuff and call those two lines below
// in the callback of the asynch operation.
}
else {
// Send JSON to result
res.json(inputArray);

// Close MySQL connection
connection.end();
}
};
});


I'm thinking something like this might work:

function processTask(){ // Which function creator to use?
// I do asynch stuff and call those two lines below
// in the callback of the asynch operation.
}
else {
// Send JSON to result
res.json(inputArray);

// Close MySQL connection
connection.end();
}
}(); // instead of the explicit function call, call the function calls itself

• Could you supply all of your code? Answers may likely be different given that you're excluding the closure which contains connection, res, taskIteration and rowLength. – Dan Pantry Jan 28 '16 at 10:22
• Those closure variables are essentially dispensable, they are part of a node.js mySQL connection and a express.js path and two ints defining for the loop. I basically just want to iterate over my results recursively, but i feel like this solution is not the very best. But if you really think that'd help i'll edit my answer. – Clemens Himmer Jan 28 '16 at 10:27

Why not just

connection.query(queryString, function (err, rows, fields) {
if (err) return throwSQLError(err, req, res, connection);

rows.forEach(function (row) {
// do what you need to with each row;
});

/* or maybe even
var result = rows.map(function (row) {
// do what you need to with row and return it
});
and then do something with result
*/
res.json(inputArray); // Not clear from the question where inputArray has come from
connection.end();
}

• I think my initial question was articulated really bad, i edited in hope of improvement. – Clemens Himmer Jan 28 '16 at 15:42