I currently have this situation...
function loop (num1, callback) {
for (i = 0; i < num1; i++) {
console.log("loop count: " + i);
callback();
}
}
Which is currently outputting the following sample results:
loop count: 1
loop count: 2
loop count: 3
...
loop count: num1 - 1
callback output 1
callback output 2
callback output 3
...
callback output num1 - 1
What I would like it to do is wait until each callback has finished executing and outputting its result before moving onto the next item in the loop. i.e. as per the sample output below:
loop count: 1
callback output 1
loop count: 2
callback output 2
loop count: 3
callback output 3
...
loop count: num1 - 1
callback output num1 - 1
Does anyone know how I can achieve this sequential / synchronous mode of operation in my function?
Thanks in advance for the help!
UPDATE...
Ok so the call back function is being called like so...
loop(10, updateDB);
And the callback function passed to loop is as follows...
function updateDB(sql_string, responseObject) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'password',
database : 'database',
});
connection.connect();
var query = sql_string;
connection.query(query, function(err, results) {
connection.end();
if (err) {
console.log(err);
responseObject.push({"queryStatus":"FAIL"});
}
if (err == null) {
console.log('Changed ' + results.changedRows + ' rows');
responseObject.push({"queryStatus":"PASS"});
}
});
};
callback output icome from?forloop. You cannot pause it to manually callnext()as you can in other languages. Besides, depending on the value ofnum, using callback could end up in an error after reaching the maximum nesting depthcallback. Its obviously synchronous.