【问题标题】:Javascript function returning undefined, Integer value expected [duplicate]Javascript函数返回未定义,预期整数值[重复]
【发布时间】:2021-04-11 00:09:44
【问题描述】:

您好,我正在调用函数 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
});

如何得到想要的输出

【问题讨论】:

  • @Ivar 我认为它与您提供的此链接有关,但我不知道如何使用我当前的代码执行此操作,因为我没有更多地使用 JS
  • 您的问题是您传递给myDB.transactiontransaction.executeSql 的函数被称为异步。这意味着您的代码会继续运行并因此返回 length before length = results.rows.length 被执行。您不能简单地同步代码,因此您需要正确处理回调。这还包括对您拨打get_location_tcount 的位置所做的更改,您未在此处显示。
  • 这是 JavaScript 工作原理的基础,因此我建议您尝试理解该帖子,以解决您的问题并更好地了解 JavaScript,这样您就不必遇到这些以后再出问题。
  • 谢谢@Ivar,感谢您向我详细说明原因。我会浏览你分享的帖子。

标签: javascript sqlite cordova


【解决方案1】:

您可以将回调函数作为参数传递给 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 代替回调函数。

【讨论】:

  • var t_count = 0; get_location_tcount(2, function(result) { t_count = result; } //再次给出 undefined
  • 您是否在 get_location_tcount 函数体内调用了回调函数?
  • ` get_location_tcount(2,function(total_count){ t_count = total_count; });` 我就是这样@Ahmad Akhmiev
猜你喜欢
  • 2013-06-26
  • 1970-01-01
  • 2017-02-07
  • 2014-03-05
  • 2018-12-05
  • 2018-12-05
  • 1970-01-01
  • 2022-11-26
  • 1970-01-01
相关资源
最近更新 更多