I'm trying to use a variable in my callback function for an SQL query in ExpresJS.
for (i = 1; i <= 10; i++) {
sql.query(testQuery, function(testQueryError, testQueryResult) {
if (testQueryError) {
console.log("ERROR");
} else {
//Use the index here, or some other variable outside of async function
console.log("NO ERROR");
}
});
}
However, the result I am achieving doing this yields 10 as the index within all of my SQL queries. My theory is that all of the SQL queries are initiated, and due to their async nature process while the loop continues to progress. The loop reaches its max index, 10, then the async function as it continues to execute looks to pull the variable for use. At that time it's 10, so it uses 10, instead of the current index at the time when the SQL query was initiated.
I'm not sure how to handle this. I've read the SQL documentation (https://github.com/mysqljs/mysql) which describes the callback function. It can take an optional "values" parameter but that seems to be for inserting variables into the SQL query. I can't seem to find a way to just pass some variable into the callback for general use. Can someone help me out?