I'm playing with node.js and node-mysql and I'd like to understand the following:
connection.connect(function(err) { if (err) throw err; });
console.log(" beginn insert "+ Date() );
for (var i=0;i<200;i++){
connection.query('INSERT INTO animals SET ?', {name: "tiger!"});
}
connection.end();
console.log(" end insert " + Date() );
The output is always ' beginn insert ' immediately followed by ' end insert ' and then only the database starts working. How is it possible that these node-mysql statements seem to be non-blocking?
Thanks, Felix
Use Async; something like the following:
console.log(" beginning insert "+ Date() );
// create your queries as an array of objects
queries = [];
for (var i=0;i<200;i++){
queries.push({name: "tiger!"});
};
async.map(queries, myQuery, function(err, data){
// Here all of your queries are done
connection.end();
console.log(" end insert " + Date() );
});
function myQuery(name, callback){
connection.query('INSERT INTO animals SET ?', [name], function(err, result) {
if(err){
console.error(err);
callback(err, null);
}else{
callback(null, result);
}
});
}