0

I would like to send a value via the variable numOfComment when the comment grater than the previous one. I got answer when I put inside the query but it's not work outside of query. I can't also continue/break it inside the query. Please help me

        if(domainName.includes(givenUrl)){
            tmpDomain = domainName;
            con.query("SELECT comment FROM comments WHERE domain=?", tmpDomain, function(err, result, feild){
                tmpNumOfComment = result.length;
                if(tmpNumOfComment>numOfComment){
                    numOfComment = tmpNumOfComment;
                }
            });

            console.log('Number Of Comment : '+numOfComment);
        }
  • Your database operation is non-blocking and asynchronous. The ONLY place the result is valid is inside the callback or in any function you call from the callback and pass the result to. You are logging the value BEFORE it has been set because that async callback is called some indeterminate time in the future. This is how non-blocking asynchronous operations work in Javascript. – jfriend00 Sep 01 '17 at 20:25

1 Answers1

0

The query has a callback. This means that is very likelly that your console.log command get executed before the return from the database. Try running this way

        if(domainName.includes(givenUrl)){
        tmpDomain = domainName;
        con.query("SELECT comment FROM comments WHERE domain=?", tmpDomain, function(err, result, feild){
            tmpNumOfComment = result.length;
            if(tmpNumOfComment>numOfComment){
                numOfComment = tmpNumOfComment;
                console.log('Number Of Comment : '+numOfComment);
            }
        });


    }
Luiz Paulo
  • 401
  • 6
  • 14
  • Thanks Luiz Paulo for your Answer. This code will work and I used this code before. But I don't want this. I want to send this value to the outside of this call back function. I just check whether is it work for console.log? – Md Misbauddin Chowdhury Sep 01 '17 at 22:15