【发布时间】: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.transaction和transaction.executeSql的函数被称为异步。这意味着您的代码会继续运行并因此返回lengthbeforelength = results.rows.length被执行。您不能简单地同步代码,因此您需要正确处理回调。这还包括对您拨打get_location_tcount的位置所做的更改,您未在此处显示。 -
这是 JavaScript 工作原理的基础,因此我建议您尝试理解该帖子,以解决您的问题并更好地了解 JavaScript,这样您就不必遇到这些以后再出问题。
-
谢谢@Ivar,感谢您向我详细说明原因。我会浏览你分享的帖子。
标签: javascript sqlite cordova