Asynchron Errorhandling inside $.each

和自甴很熟 提交于 2019-12-12 03:23:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!