简体   繁体   中英

nodejs loop async callback function

I am running a cron job with node with mongodb as the database. I am trying to close db connection and exit the process once the curr_1 each loop has executed completely.

However the exit() is called while function_2 is being executed. I understand this is due to the callback and is async in nature.

How do I make sure exit is called only once the curr_1.each is complete? Any solution without promises?

function function_1(obj){
    var curr_1 = coll_1.find({})
    curr_1.each(function(err, doc) {
        function_2(doc)
    }); 
    exit(obj)
}
function function_2(obj) {
    coll_2.findOne({}, function(err, document) {
        dosomeprocess(obj)
    })
}
function exit(obj) {
    // Close connection
    console.log('closing connection')
    obj.db.close();
    process.exit();
}

It's a job for Node async ....

For example:

async.each(
  curr_1, // the collection to iterate over
  function(doc, callback) { // the function, which is passed each
                            // document of the collection, and a
                            // callback to call when doc handling
                            // is complete (or an error occurs)
    function_2(doc);
  },
  function(err) { // callback called when all iteratee functions
                  // have finished, or an error occurs
    if (err) {
      // handle errors...
    }

    exit(obj); // called when all documents have been processed
  }
);

Without using any library:

function function_1(obj, callback) {
     var curr_1 = coll_1.find({})
            curr_1.each(function(err, doc) {
            callback(err, doc);
    });

}

function function_2(err, obj) {

    coll_2.findOne({}, function(err, document) {
         dosomeprocess(obj)
         exit(err, obj);
    })
}

function exit(err, obj) {
   // Close connection
    console.log('closing connection')
    obj.db.close();
    process.exit();
}

function_1(obj, function_2);

Using async module

var async = require('async');

async.waterfall([
    function function_1(callback) {
    var curr_1 = coll_1.find({})
    curr_1.each(function(err, doc) {
    if (err) {
        callback(err, null)
    } else {
      allback(null, doc)
    }

   });
  },
  function function_2(obj, callback) {
    coll_2.findOne({}, function(err, document) {
    if (err) {
       callback(err, null);
    } else {
       dosomeprocess(obj)
       callback(null, obj);
    }

   })
 }

], function done() {
   obj.db.close();
   process.exit();

});

Simply give a condition in your loop using counter.

function function_1(obj){
var curr_1 = coll_1.find({})
var curr_1Length = curr_1.length;
var counter  = 0;
curr_1.each(function(err, doc) {
++counter;
//Check condition everytime for the last occurance of loop
if(counter == curr_1Length - 1){
exit(obj)
}
    function_2(doc)
}); 
}

Hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM