0

Unable to assign a value in a javascript function while fetching from sqlite.

For Eg: This code in not working

function bookContent(dtb) {

    var bkContent = '';     

    dtb.all("SELECT count(*) ttlRw FROM books;", function(err, row) {

        if (err)
        bkContent = "Error SQL";
        else
        {           

            if(parseInt(row[0].ttlRw)>0)
            {
                bkContent = row[0].ttlRw + " rows";
            }
            else
            bkContent = 'No rows found!';                   
        }

    });

    return bkContent;

}

It's returns an empty value.

This is working

function bookContent(dtb) {

    dtb.all("SELECT count(*) ttlRw FROM books;", function(err, row) {

        if (err)
        document.getElementById("bookCnt").innerHTML = "Error SQL";
        else
        {           

            if(parseInt(row[0].ttlRw)>0)
            {
                document.getElementById("bookCnt").innerHTML = row[0].ttlRw + " rows";
            }
            else
            document.getElementById("bookCnt").innerHTML = 'No rows found!';                    
        }

    });

}

I want the first one work. Please tell me, where i am wrong.

Jay
  • 673
  • 3
  • 7
  • 21

2 Answers2

1

You're returning a value before the asynchronous dtb.all() finishes. You need to pass a callback to bookContent and call it when the database query finishes.

var globalBkContent = "";  
function bookContent(dtb, callback) {
    dtb.all("SELECT count(*) ttlRw FROM books;", function(err, row) {

        if (err)
        return callback("Error SQL");
        else
        {           

            if(parseInt(row[0].ttlRw)>0)
            {
                return callback(false, row[0].ttlRw + " rows");
            }
            else
            return callback("No rows found!")           
        }

    });
}

var dtb = new DatabaseInstance();//Or whatever your dtb variable is defined as.
bookContent(dtb, function(err, bkContent) {
    if(err) throw(err);
    globalBkContent = bkContent;
    console.log(bkContent); //Here your bkContent & globalBkContent are both accessible and have the correct values. 
    //Make sure you don't do anything with globalBkContent until it is set by this function.
})

//If I access globalBkContent outside the callback above then it will still be an empty string.
forrestmid
  • 1,494
  • 17
  • 25
  • Thanks @forrestmid for your reply. But still how can i get the bkContent value outside bookContent(); Like assign to a global variable. – Jay Feb 04 '17 at 13:54
  • @Jay Your question doesn't ask anything about a global variable. I'll modify my answer to allow for a global variable, but your primary issue is because you're returning the function before the asynchronous portion has finished. – forrestmid Feb 04 '17 at 17:36
  • @Jay Additionally, you can't do anything with bkContent until your callback is returned, simply because it hasn't been set yet. You need to read up on how asynchronous functions work in Node if you want to be able to program in it. It's vitally necessary to know how to nest asynchronous functions in order to accomplish a goal in the programming language. – forrestmid Feb 04 '17 at 17:40
  • Thanks @forrestmind. Thanks for the help. – Jay Feb 04 '17 at 23:44
  • SORRY! It's not working – Jay Feb 11 '17 at 00:20
  • @Jay What, exactly, is "not working?" Why did you mark an answer if it wasn't working? What is the problem you're experiencing? – forrestmid Feb 11 '17 at 03:39
  • Real sorry about that. i want the content of the globalBkContent variable available outside bookContent function. That's not happening. I put two console.log for globalBkContent. 1st one beneath console.log(bkContent); and the 2nd one after the function call. The 1st one works. but the 2nd return an empty string. And seems like the 2nd one executes first. I want the 2nd one working, means the content of the globalBkContent variable should be available outside the function call, after the function call. – Jay Feb 11 '17 at 08:12
  • @Jay You're still not understanding how asynchronous calls work. The only way to access the value you want is within the function that has the `console.log`. So, you have to chain your callbacks in order to use information from your first callback in further callbacks. Check [this](http://callbackhell.com/). Read through it and see if you can understand it, because if you don't you'll always have a really hard time programming in javascript. – forrestmid Feb 11 '17 at 11:44
  • @forrestmind, Thanks for your patience and help. Let me check the link – Jay Feb 11 '17 at 14:46
  • Yes. Now i got it. Thanks again – Jay Feb 11 '17 at 15:38
0

I have basic knowledges Nodejs, but I think it returns empty value because in the first code your return bkContent out of the dtb.all() function. But in the second code, you write in the function.

  • Thanks @Teymur Mardaliyer Lennon for your reply. I tried it inside the dtb.all. But then the function returns an 'undefined' msg; – Jay Feb 03 '17 at 22:24
  • @Jay may be it will help you? http://stackoverflow.com/questions/25399725/nodejs-get-async-return-value-callback or http://stackoverflow.com/questions/18361930/node-js-returning-result-from-mysql-query or you need just return value? – Teymur Mardaliyer Lennon Feb 03 '17 at 23:27
  • Also you can test seems like this `var result = dtb.all("SELECT count(*) ttlRw FROM books;", function(err, row) {...... return bkContent; }); console.log(result);` hm? – Teymur Mardaliyer Lennon Feb 03 '17 at 23:29
  • i tried it. but it's returns a DB object. Not the values returns from bkContent. I will try the links you specified above. Thanks once again for the help. – Jay Feb 03 '17 at 23:44