简体   繁体   English

从函数返回时我的警报未定义

[英]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. 我试图从查询中返回值,但是当我提醒我的var时说它未定义。 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. 问题是您将len返回到错误的函数。 In this case len is being returned to the function defined by function (tx, results) { . 在这种情况下, len将返回到由function (tx, results) {定义的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. 编辑:我忘记了异步运行的javascript。 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. 我已经更改了代码,因此它应该更新test并发出警报,但是如果您希望代码按最初的计划运行,则必须做一些特殊的事情,或者只是将所有代码放在回调中。

It looks like a closure issue to me. 对我来说,这似乎是一个关闭问题。 See here Javascript Closure. 请参见此处Javascript闭包。 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. 因为您的目的是警告len的值,所以我创建了以下代码,它对我有用,可以正确警告var len。 Although you have to modify the dbTran function and add in the necessary codes. 尽管您必须修改dbTran函数并添加必要的代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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