问题
I am on server side Node.js and somehow caught up in the callbacks. I use the following function to insert Data in the Table with the mysql pkg:
connection.query('INSERT INTO tableName SET ?', post, function(err, result)
{
if (err) {
if (err.code === 'ER_DUP_ENTRY')
{ }
else
{ throw err; }
}
});
I want to log how many duplicate entries are there without stoping the loop which calls this above function by an $.each.
It says here that i have 3 possibilities: throw, callbacks and EventEmitter. Throwing won't work, since this stops everything. I tried it with callbacks, but because i am in the callback from the $.each i could'nt find away in the above scope. I didn't try with a static EventEmitter since i don't know how to return any value from an $.each selector, except the selected Data.
Any suggestions would be appriciated.
回答1:
Nest everything in a closure and count the finished queries in the callback, so that you know when is the last query finished:
(function(){
var errors = 0;
var started = 0;
var successful = 0;
$.each(..., function(){
started++;
connection.query('INSERT INTO tableName SET ?', post, function(err, result)
{
if (err) {
if (err.code === 'ER_DUP_ENTRY')
{ errors++; }
else
{ throw err; }
} else { successful++;}
if (started == successful + errors) {
// all done
console.log(errors + " errors occurred");
}
});
});
})();
来源:https://stackoverflow.com/questions/35246797/asynchron-errorhandling-inside-each