Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for data from async nested Functions within JQuery $.each in Javascript

this is a follow up question to Asynchron Errorhandling inside $.each. As mentioned in the comments there, i want to handle data after the last async job from a $.each loop.

So for instance:

  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");
      }
    });
  });

In this case everything logs out properly when the // all done comment is reached. But what if i want to use this data later on instead of just logging it out.

Is there a way to wait for this data outside of the $.each scope? Or do i always have to handle everything in the nested function?

like image 937
k4yaman Avatar asked Jun 26 '26 22:06

k4yaman


1 Answers

You can use promises instead

var promises = [];

$.each(..., function() {
    var promise = new Promise(function(resolve, reject) {;
        connection.query('INSERT INTO tableName SET ?', post, function(err, result) {
            if (err) {
                resolve(err.code);
            } else {
                resolve(result);
            }
        });
    });
    promises.push(promise);
});


var result = Promise.all(promises);

And then when you want to use the data, you do

result.then(function(data) {
    // use data array looking like ["result data", "result data", "ER_DUP_ENTRY" .. etc]
})
like image 191
adeneo Avatar answered Jun 29 '26 11:06

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!