Asynchronaus calls - process.nextTick issue

43 views
Skip to first unread message

Mateusz Woziu

unread,
Feb 4, 2015, 5:06:13 AM2/4/15
to nod...@googlegroups.com
Hi there, I have two tasks to do:
1. Mongo Call ---> simple find with query
2. Searching in the result of Mongo find with forEach and making another request to different collection..
3. res.send changes which have been done in forEach loop.

For now it looks like that:

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

            currData = result;
           
        });
 find(currData); 
   res.send(currData);


and find is a function() like  :

function find(db) {
    db.forEach(function (prevResult) {
        db.collectionOther.find({ MID: commId }, function (error, result) {
            result.forEach(function (r) {  
       some calculations;
                if (condition) {
                  prevResult= Calculations; 
                }               
            });
        });
    });
     

I tired to do it whit process.nextTick but failed. Could someone help mi to make the calls be done after each other and not at the same time?

Bruno Jouhier

unread,
Feb 6, 2015, 3:16:25 AM2/6/15
to nod...@googlegroups.com
Your control flow is wrong. I've added a few console.log in your code below. Output should be:

BEFORE FIND
BEFORE DB FOREACH
AFTER FIND
DB FOREACH CALLBACK
AFTER CURRDATA ASSIGNMENT

This should explain why currData is still undefined after the find call.

Bruno

On Wednesday, February 4, 2015 at 11:06:13 AM UTC+1, Mateusz Woziu wrote:
Hi there, I have two tasks to do:
1. Mongo Call ---> simple find with query
2. Searching in the result of Mongo find with forEach and making another request to different collection..
3. res.send changes which have been done in forEach loop.

For now it looks like that:

 db.collection.find().sort({ "rank": order }).skip(pagenumber).limit(5, function (err, result) { 
            currData = result;
 console.log("AFTER CURRDATA ASSIGNMENT");
           
        });
console.log("BEFORE FIND"); 
 find(currData); 
console.log("AFTER FIND");  
   res.send(currData);


and find is a function() like  :

function find(db) {
console.log("BEFORE DB FOREACH"); 
    db.forEach(function (prevResult) {
console.log("DB FOREACH CALLBACK");  
Reply all
Reply to author
Forward
0 new messages