suresh gopal
suresh gopal

Reputation: 3156

How to identify Loop is completed

I want to minimize following code. Working in node js

var each = 0;
var final = {};
// myLoop have some array values;
myLoop.forEach(function(row) {

    //data retrive from db
    db.query('SELECT * FROM test where type=?',[row.type], function(err, result) {
        final[each] = result;
        each++;
        if (each == myLoop.length) {
           return final;
        }
    });

});

Above code working fine, but trying to avoid if (each == myLoop.length) condition. Is anything available to identify the loop is completed?

Is possible something like below:

myLoop.forEach(function(row) {
    //do needs
}).done({
    return final;
});

Upvotes: 2

Views: 132

Answers (4)

mevernom
mevernom

Reputation: 90

Looks like your need should cooperate with DB side.

Even the async.each determines if all callbacks are completed through counting

If you use MongoDB with node driver, you can try to issue your queries in aggregation

Upvotes: 1

V31
V31

Reputation: 7666

You can make use of the callback function. It will get executed only when everything is completed.

 // Call the function
 loopTheArray(myLoop,function(final){
    //Do whatever you want with final
 });

function loopTheArray(myLoop,callback){
    var final = {},each=0;
    myLoop.forEach(function(row) {
        //data retrive from db
        final[each] = row;
    });
    callback(final);
}

Working Fiddle

Upvotes: 0

stakolee
stakolee

Reputation: 950

Well in the short term, you could make use of forEach's index:

var final = {};
// myLoop have some array values;
myLoop.forEach( function( row, index ) {
    //data retrive from db
    final[ index ] = row;
    if (index === myLoop.length) {
        return final;
    }
});

And why are you returning 'final'? Were you hoping to do something like trigger an event instead?

Upvotes: 0

vodolaz095
vodolaz095

Reputation: 6986

You can do this via Caolan's Async library (or you can take a look how it is done in this lib) - https://github.com/caolan/async#each

// assuming openFiles is an array of file names 

async.each(openFiles, function( file, callback) {

  // Perform operation on file here.
  console.log('Processing file ' + file);

  if( file.length > 32 ) {
    console.log('This file name is too long');
    callback('File name too long');
  } else {
    // Do work to process file here
    console.log('File processed');
    callback();
  }
}, function(err){
    // if any of the file processing produced an error, err would equal that error
    if( err ) {
      // One of the iterations produced an error.
      // All processing will now stop.
      console.log('A file failed to process');
    } else {
      console.log('All files have been processed successfully');
    }
});

Upvotes: 0

Related Questions