Skip to content
  • 0 Votes
    4 Posts
    4k Views
    julianJ

    Is this for a hook of some sort? Please paste the entire function, and which hook you're subscribing to...

  • 0 Votes
    2 Posts
    2k Views
    yariplusY

    for is synchronous, so you will need to require the async library. That library has an async.each() function which is an asynchronous version of forEach.

    You will want to read up on it here.
    https://github.com/caolan/async#each

    var async = require.main.require('async'); function doLast(){ console.log(" STRING "); } var array = [a, b, c]; async.each(array, function(value, next){ // The value is sent here, not the index, if you really need the index, you can use forEachOf() or do array.indexOf(value). db.getObject(------,function(err,returnData){ //in this method modify string in some way console.log("METHOD"); // Call next() to let the the app know that the async operation is complete. next(); }); // When all async operations are complete, run doLast. }, doLast);
  • 0 Votes
    1 Posts
    2k Views
    K

    Well, I have this issue that I need to do following things:
    1.Mongo Find
    2. Foreach
    3. MongoFind
    4 one more Foreach.

    because of asynchronaus mongo calls it is difficult to get proper result, however process.nextTick should handle this problem and still I have problem:

    function find(dbComm) {

    dbComm.forEach(function (current) { id= parseFloat(current.ID); db.anotherCollection.find({ ID: id}, function (error, result) { result.forEach(function (rank) { if (parseFloat(result.ID) == parseFloat(current.ID)) { rank.rank = 'Some calculations'; } }); }); });

    }

    app.get('/someparams', function (req, res) {

    db.collection.find().sort({ "rank": order }).skip(pagenumber).limit(5, function (err, result) { process.nextTick(function () { find(result, function () { }) }); process.nextTick(function () { res.send(result); }); });

    And on client side I should recive an array where the rank equals 'Some Calculations'
    but unfortunetly it is not...
    However...! If I add setTimeout(function(){}) before res.send(result) (and res.send(result) will be placed inside setTimeout) it actually does work and on client side I recive data with "Some Calculations" but it is just timeout and it fails sometimes and client dont recive "Some Calculations"
    if I put process.nextTick instead of setTimeout it doesnt work and "Some calc..." are not sent.

    Something is beeing done eralier then it should (probably in forEach in find() function)
    and my question is how to deal with it? maybe I should put process.nextTick in different function ?