Javascript 函数返回未定义,应为整数值

Javascript function returning undefined, Integer value expected

嗨,我正在调用函数 get_location_tcount(1);谁的声明就像

function get_location_tcount(id,callback) {
myDB.transaction(function (transaction) {
    var t_sql = 'select * from tbl_locations where location_structure_id = "' + id+ '"';
    transaction.executeSql(t_sql, [], function (tx, results) {
        var length = results.rows.length;
        callback(length);
    }, null);
});
}

我是这样称呼它的

var t_count = 0;
get_location_tcount(1,function(total_count){
    alert(total_count); // Alerting the value
    t_count = total_count; // but not setting in variable t_count
});

如何得到想要的输出

您可以将回调函数作为参数传递给 get_location_tcount,并在您有长度时调用该回调函数。如果数据库调用失败,还要确保调用回调函数。

function get_location_tcount(id, callback) {
myDB.transaction(function (transaction) {
    var t_sql = 'select * from tbl_locations where location_structure_id = "' + id + '" and location_house_id!= "0"';
    transaction.executeSql(t_sql, [], function (tx, results) {
        var length = results.rows.length; // till here length variable getting value
       callback(length);
    }, null);
});
}

// somewhere else in your code
get_location_tcount(2, function(result) {
  console.log(result); //should be your length
}

我同意 Ivar 的观点,您应该阅读有关异步调用的内容。您可以使用 Promise 或 async/await 而不是回调函数。