I need to execute a series of MySQL inserts in a loop, and then do something after they are all completed. However, I'm not sure where to put the callback --
for (var q=0; q<things.length; q++)
{
thing
.create({
active_time: time
rule: rule
next: next_object,
percentage: object.percent,
enabled: 1,
})
.complete(function(err, newSchedule) {
console.log('thing added successfully');
})
}
I can't put it in the .complete
section, because it needs to occur after all of them. How can I ensure that they are all done before proceeding?
EDIT: I've started using AsyncJS but it seems that the MySQL queries will callback before they are finished. Here is the new code:
if (valid) {
async.each(arrayOfObjects, tools.submitThing, function()
{
console.log("finished submissions")
});
and
exports.submitThing = function(thingObject, callback) {
thing
.create({
active_time: time
rule: rule
next: next_object,
percentage: object.percent,
enabled: 1,
})
.complete(function(err, newSchedule) {
console.log('thing added successfully');
})
callback();
}
The server console shows that the message "submissions completed" registers before the MySQL insertions. Any way to get around this?