0

I can not understand why my global variable declared in function remains empty at the end of function despite the fact that it was changed inside the transaction

Please help to return the result of the transaction back in to my function

function () {
var db;
var rowsNameList = [];    
db = openDatabase('cwdb', '1.0', '', 10 * 1024 * 1024);

function getRowsNames(result){

    for (var i = 0; i < result.rows.length; i++) {
        for (var rowName in result.rows[i]) {
            rowsNameList.push(rowName);
        }
    }        
};

db.transaction(function (tx) {
    tx.executeSql("SELECT * FROM TreeEls WHERE parent = '#'",
        [],
        function (tx, result) {
            console.info(result)
            getRowsNames(result); 
            console.log(rowsNameList);
        },         
        function (tx, error) {
        }
    );
});

console.log(rowsNameList);

return {}

Inside transaction console.log shows that array consists of 5 elements, so i have used global variable, but console.log at the end of function shows empty array and i have no idea why?

  • The callbacks are asynchronous. See [How do I return the response from an asynchronous call?](//stackoverflow.com/q/14220321) – wOxxOm Aug 14 '17 at 18:11
  • Thank you, it has become much clearer what is happening, but this does not solve my problem( At the end of my function i must return object that must know the rowsNameList, but unfortunately i cannot return it from .then() – Виталий Белоусов Aug 14 '17 at 20:18
  • 1
    You need to switch your entire workflow with the database to Promises or async/await or callbacks because that's the only way. – wOxxOm Aug 15 '17 at 04:03

0 Answers0