简体   繁体   中英

my alert is undefined when returning from function

Im trying to return the value from a query but when i alert my var it says its undefined. Below is my code

function countRows(){
    db.transaction(function (tx){
        tx.executeSql('SELECT id FROM Courses', [], function (tx, results) {
            var len = results.rows.length;
            return len;
        });
 });

}

var test = countRows();
alert(test);

The problem is that you are returning len to the wrong function. In this case len is being returned to the function defined by function (tx, results) { . The best solution I cn thing of is to add a callback to return the answer.

function countRows(callback){
    db.transaction(function (tx){
        tx.executeSql('SELECT id FROM Courses', [], function (tx, results) {
            var len = results.rows.length;
            callback(len);
        });
     });

}

var test;
countRows(function(len){
    alert(len)
    test = len;
});

Bear in mind that this code has not been tested for this case.

EDIT: I forgot about the javascript running asynchronously. I have changed the code so it should update test and make the alert, but you will have to do something special or just put all of your code in the callback if you want the code to run as originally planned.

It looks like a closure issue to me. See here Javascript Closure. As your purpose is to alert the value of len, I have created the following code and it works for me, the var len is alerted correctly. Although you have to modify the dbTran function and add in the necessary codes.

function countRows()
{    
    var dbTran = function() { var len = 123; alert(len);};         
    return dbTran();
}    
countRows();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM