user3488862 user3488862 - 4 months ago 15
Node.js Question

How can I make node js synchronize?

I used promise as suggested but still I have a problem that I can console.log my array.

here is what I did:

exports.getData = function(request, response) {

userEmail = request.body.user;

function delay(ms){ // takes amount of milliseconds
return new Promise(function(resolve, reject){
setTimeout(function(){ // when the time is up
resolve(); // change the promise to the fulfilled state
}, ms);
});
}

Wish.find({userEmail}).exec( function(err, docs) {
//console.log("docs "+docs);
var wishArray = new Array();


for (var i=0; i<docs.length; i++) {
if (docs[i].sub=='party') {
var id = docs[i].num;
delay(100).then(function(){
Party.find({id}).exec(function(err, details) {
console.log("5");
wishArray.push(details);
});
});
}
}
});
delay(700).then(function(){
console.log(wishArray);
});

}


I tried make the number of the second delay larger but it didn't work.
anyone has any idea how can I fix it?

Answer

You can avoid logging untill wishArray is fully populated, this way.

exports.getData = function(request, response) {
userEmail = request.body.user;

Wish.find({userEmail}).exec( function(err, docs) {
    console.log("docs "+docs);
    var wishArray = new Array();
    for (var i=0; i<docs.length; i++) {

        if (docs[i].sub=='party') {
            console.log("--------------------"); 
            var id = docs[i].num;
            Party.find({id}).exec(function(err, details) {
                wishArray.push(details);
                  if(wishArray.length == docs.length){
                      console.log(wishArray);
                  }

            });
        }  
    }
    console.log("***************************"); 

});  

}

in many other complex use cases people used array of deferred queries. but your case is simple one you can catch hold of it just by length of array.

Comments