\$\begingroup\$
\$\endgroup\$
2
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; var taskIteration = 0; // Iterate over all tasks with a recursive function var processTask = function () { if (taskIteration < rowLength) { // I do asynch stuff and call those two lines below // in the callback of the asynch operation. taskIteration++; processTask(); } else { // Send JSON to result res.json(inputArray); // Close MySQL connection connection.end(); } }; processTask(); });
I'm thinking something like this might work:
function processTask(){ // Which function creator to use?
if (taskIteration < rowLength) {
// I do asynch stuff and call those two lines below
// in the callback of the asynch operation.
taskIteration++;
processTask();
}
else {
// Send JSON to result
res.json(inputArray);
// Close MySQL connection
connection.end();
}
}(); // instead of the explicit function call, call the function calls itself
Clemens Himmer
asked Jan 28, 2016 at 10:07
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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();
}
answered Jan 28, 2016 at 15:29
-
\$\begingroup\$ I think my initial question was articulated really bad, i edited in hope of improvement. \$\endgroup\$Clemens Himmer– Clemens Himmer2016年01月28日 15:42:41 +00:00Commented Jan 28, 2016 at 15:42
default
connection
,res
,taskIteration
androwLength
. \$\endgroup\$