Sunday, 16 April 2017

Using AsyncJS to wait for while loop

I have function that is using while loop and than it is returning value, but Node.js wont wait for method to finish while loop because Node has non blocking nature. I wanted to implement AsyncJS to fix the issue, I've tried couple of stuff but none of it worked. How I should implement async for the following code:

...
        var id = idNovePartije();
                trenutniMec.idMeca = id;
                trenutniMec.nedostajeIgrac = true;
                trenutniMec.status = "Ceka se igrac";
                trenutniMec.fbIdPrvogIgraca = docs2.fbid;
                trenutniMec.socketIdPrvogIgraca = socketId;

                trenutniMec.save(function(err) {
                    if (err){
                        res.send(err);
                    }
                });
...

function idNovePartije(){
var novId = "5";
        mec.findOne({idMeca : novId}, 'idMeca', function(err, docs){
            if(docs){
                do{
                    novId = randomGenerisanje(1);
                    var docsOutside = null;
                    mec.findOne({idMeca : novId}, 'idMeca', function(err, docs2){
                        if(docs2){
                            docsOutside = docs2;
                        }
                        else{
                            docsOutside = null;
                        }
                    });
                }while(docsOutside != null);
            }
        });
return novId;   
}



via Slay29

No comments:

Post a Comment